None Blocking setTimeout(fn, 0)
<p>I have been using JavaScript as a tool for many years now, but only recently have I begun programming applications with it. After watching <a href="http://www.youtube.com/watch?v=QgwSUtYSUqA" rel="nofollow">Crockford on JavaScript - Level 6: Loopage</a> I have begun to appreciate the Event Loop and the style of not blocking. To better get to grips with this I have gone back to an app where I am believe I have a badly designed area of code.</p>

<p>The application downloads an ~45KB JSON file (minified, uncompressed) containing ~20 elements, so on average each element has about 2.25KB of data. The download takes place every minute, as well as being manually triggered, at which point the new array replaces the old array. Every 15 seconds the DOM is cleared out and the array is iterated over. Calculations and logic are performed on the data to create groups of DOM elements to be inserted into the DOM.</p>

<p>Rather than doing:</p>

<pre><code>for (int i = 0; i &lt; array.length; i++) {
  // Perform logic
}
</code></pre>

<p>How would I implement it in a none blocking fashion? So far I have come up with:</p>

<pre><code>var performLogic = function performLogic(element) {
  // Perform logic
}

var counter = 0;
var iterator = function iterator() {
  counter += 1
  if (counter &lt; array.length) {
    performLogic(array[counter]);
    setTimeout(iterator, 0);
  }
}

setTimeout(function() {
  counter = 0;
  iterator();
}, 0);
</code></pre>

<p>I can't get my head around it. I know this will fail if the data was downloaded in between the <code>performLogic()</code> calls, as the array length <em>may</em> alter, regardless the group of data won't be from the same array.</p>
