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?

1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

To put it simply, the closure remembers the reference to a variable, not the value of it.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.