Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>1) You set all the timeouts to last 1 second at the same time. The loop doesn't wait for the timeout to occur. So you have 5 timeouts that all execute at the same time.</p> <p>2) When the timeouts execute, the loop is long since complete and <code>i</code> has become 5. So once they execute, they all print "5"</p> <p>3) <code>document.write()</code> writes somthing onto the page, in the same place it executes. I.e. if you have <code>&lt;script&gt;document.write("xyz")&lt;/script&gt;</code> in the middle of a piece of text, it'll write "xyz" in the middle of the text. The timeouts, however, are not necessarily anywhere on the page. They exist only in code.</p> <p>Here's a solution that's as close to yours as possible: <a href="http://jsfiddle.net/rvbtU/1/">http://jsfiddle.net/rvbtU/1/</a></p> <pre><code>var container = document.getElementById("counter"); for(i = 0; i &lt; 5; i++) { setTimeout("container.innerHTML += '" + i + " ';", 1000 * i); } </code></pre> <p>However, that solution uses setTimeout's ability to evaluate a string as javascript, which is never a good idea.</p> <p>Here's a solution that uses an anymous function instead: <a href="http://jsfiddle.net/YbPVX/1/">http://jsfiddle.net/YbPVX/1/</a></p> <pre><code>var container = document.getElementById("counter"); var writer = function(number) { return function() { container.innerHTML += String(number) + " "; }; } for(i = 0; i &lt; 5; i++) { setTimeout(writer(i), 1000 * i); } </code></pre> <p>Edit: Forgot to save the 2nd fiddle. Whoops. Fixed now.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload