0

I am curious as to why and how the javascript interpreter outputs the following

5
5
5
5
5

When running this code:

for(var i=0;i<5;i++){
setTimeout(function(){console.log(i);},200);  
};

Can anyone provide a thorough explanation?

Adrian Stamin
  • 687
  • 2
  • 8
  • 21
  • possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – thefourtheye Mar 21 '14 at 10:31

2 Answers2

4

It's to do with chronology.

Remember the timeout is a synchronous operation that is delayed, so by the time it runs, it consults i and finds its value to be 5. This is because the last action of the (synchronous) loop was to set its value to 5: it reached 4 (the last iteration of the loop) and then the i++ made it 5.

If you want to output 0-4 but retain the timeout, you need to capture the current, iterative value of i at the time you create your timeout. You can do this by passing it into an immediately-executing function:

for(var i=0;i<5;i++)
    setTimeout((function(i) { return function(){ console.log(i); }; })(i),200);
Mitya
  • 33,629
  • 9
  • 60
  • 107
0

I think it helps to see that in the original example the closest scope for variable i, when called inside log , it's the global scope.Considering that and the fact that the for and setimeout are synchronous operations , executed one after each other, i gets to 5 and only after that is logged.

Raz
  • 11
  • 3