title: JavaScript variable binding and loop
body: <p>Consider such loop:</p>
  
  <pre><code>for(var it = 0; it &lt; 2; it++)
  {
      setTimeout(function() {
          alert(it);
      }, 1);
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>=&gt; 2
  =&gt; 2
  </code></pre>
  
  <p>I would like it to be: 0, 1. I see two ways to fix it:</p>
  
  <p>Solution # 1.</p>
  
  <p>This one based on the fact that we can pass data to setTimeout.</p>
  
  <pre><code>for(var it = 0; it &lt; 2; it++)
  {
      setTimeout(function(data) {
          alert(data);
      }, 1, it);
  }
  </code></pre>
  
  <p>Solution # 2.</p>
  
  <pre><code>function foo(data)
  {
      setTimeout(function() {
          alert(data);
      }, 1);
  }
  
  for(var it = 0; it &lt; 2; it++)
  {
      foo(it);
  }
  </code></pre>
  
  <p>Are there any other alternatives?</p>