Skip to main content

Posts

Showing posts from September, 2008

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 func