Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem is that the functions you're creating have a <em>reference</em> to the <code>i</code> variable, not a copy of its <em>value</em>, and so when they run they see <code>i</code> as it is at that point in time (past the end of the array, presumably). (More: <a href="http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html" rel="nofollow"><em>Closures are not complicated</em></a>)</p> <p>I'd recommend a completely different approach (below), but first, let's look at how to make your existing approach work.</p> <p>To do what you were trying to do, with the <code>for</code> loop, you have to have the functions close over something that won't change. The usual way to do that is to use a factory function that creates the timeout functions such that they close over the argument to the factory. Or actually, you can pass in the array element's value rather than the index variable.</p> <pre><code>for(var i in my_array) { if(my_array.hasOwnProperty(i)) { setTimeout(makeFunction(my_array[i])); } } function makeFunction(entry) { return function(){ do_something_with_data(entry); }; } </code></pre> <p><strong>But</strong>, I would probably restructure the code so you're not creating masses and masses of function objects unnecessarily. Instead, use <em>one</em> function, and have it close over an index that it increments:</p> <pre><code>// Assumes `my_array` exists at this point, and that it // has at least one entry var i = 0; setTimeout(tick, 0); function tick() { // Process this entry if (my_array.hasOwnProperty(i)) { do_something_with_data(my_array[i]); } // Move to next ++i; // If there are any left, schedule the next tick if (i &lt; my_array.length) { setTimeout(tick, 0); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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. 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.
    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