More Closure Fun!

So earlier today I got some more experience with closures. I had a loop that triggered multiple asynchronous server requests and I needed to keep track of the loop counter with respect to the iteration in which the request was made.
for (var i = 0; i < 4; i++){
  window.setTimeout(function(){alert(i);}, 0);
}
The code above will alert the number 4 a total of 4 times. I thought I could be tricky. Maybe, if I set it equal to a different variable that gets declared with 'var' in each iteration, that var will create a new variable in memory and the closure will close over each one respectively.
for (var i = 0; i < 4; i++){
  var cur = i;
  window.setTimeout(function(){alert(cur);}, 0);
}
No dice. This code will alert the number 3 a total of 4 times. The JS engine apparently doesn't close around a particular state but just keeps track of the variables in the parent functions. Whatever they are when the function gets called, that's what you'll get.
So, what's a programmer to do? Create another scope block!
for (var i = 0; i < 4; i++){
  function forScope(){
    var cur = i;
    window.setTimeout(function(){alert(cur);}, 0);
  }
  forScope();
}
Because a new instance of forScope gets created in each loop iteration, all of the alerts will get their own appropriate version of 'cur' thus you will receive the alerts 0, 1, 2, and 3 like we want.

Comments