Adrian Stamin
Adrian Stamin

Reputation: 697

Javascript setTimeOut in For Loop Behaviour

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?

Upvotes: 0

Views: 65

Answers (2)

Raz
Raz

Reputation: 11

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.

Upvotes: 0

Mitya
Mitya

Reputation: 34556

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);

Upvotes: 4

Related Questions