Friday, March 2, 2012

How to track index in 'for' loops when we have callback inside it

A typical problem faced while working with javascript code involving "for" loop with callbacks created in each run of the loop is that when the callback is actually executed the value of loop index is different than the one when the callback is created.

For Example

<script>
for(var i=0;i<10;i++){
 setTimeout(function(){alert(i);}.1000);
}
</script>

In each run of the loop a function object is created with its scope set to "global object".This global object contains variable i, the index of for loop.
All the 10 function objects will be referencing this 'i'  in the global object;
By the time call backs are run ,for loop exits and the value of i is 10.So when the call back are actually run, the value of i , which is now '10' is printed.

Simple  solution --- Anonymous function.
This works because as the scope of each function object created inside for loop now contains activation record of anonymous function (this record contains param index with value of  'i' in the current run of the loop).When the function are actually executed they refer to value of index in its scope.
 <script>
for(var i=0;i<10;i++){
 (function(index){
  setTimeout(function(){alert(index);}.1000);

 } )(i); 
}
</script>

No comments:

Post a Comment