title: jQuery deferred behaviour in for loop
body: <p>I recently asked a question about the behaviour of jquery deferred in a for loop. <a href="https://stackoverflow.com/questions/13368836/using-jquery-when-with-array-of-deferred-objects-causes-weird-happenings-with-lo/13369602#13369602">Link here</a></p>
  
  <p>I received a working answer but I don't understand why it works. </p>
  
  <p>If I have the following code:</p>
  
  <pre><code>function update(callbacks) {
      return $.Deferred(function(dfr) {
          setTimeout(function() {
              callbacks.success()
          }, 1000);
          dfr.resolve();
      }).promise();
  }
  
  function updateElements(deferreds) {
      for (var i = 0; i &lt; 5; i++) {
          (function() {
              var index = i;
              deferreds.push(update({
                  success: function() {
                      alert(index);
                  }
              }));
          })();
      }
  };
  
  (function() {
      var deffereds = [];
      updateElements(deffereds);
      $.when.apply($, deffereds).then(function() {}, function() {});
  })();​
  </code></pre>
  
  <p>It returns 5 alert windows with the values 0 through to 4. If I change the updateElements method to:</p>
  
  <pre><code>function updateElements(deferreds) {
      for (var i = 0; i &lt; 5; i++) {
          var index = i;
          deferreds.push(update({
              success: function() {
                  alert(index);
              }
          }));
      }
  };
  </code></pre>
  
  <p>It returns 5 alert windows with the value 4 only. Could someone please explain this behaviour? I'm struggling to understand where the difference comes about.</p>
  
  <p>Thanks!</p>