0

This is driving me crazy, why is this function printing 5 times "i: 6" instead of "i: 5"?

for(var i=1;i<=5;i++){
    setTimeout(function(){
        console.log("i: " + i)
    }, i*1000)
}
  • Does this answer your question? [Late binding onclick event](https://stackoverflow.com/questions/21500071/late-binding-onclick-event) – jonrsharpe Dec 31 '20 at 10:14
  • Or are you asking why the last value that gets late bound is 6 specifically? – jonrsharpe Dec 31 '20 at 10:15
  • Yes why the last value is 6!? – Felipe Briga Dec 31 '20 at 10:17
  • @jonrsharpe nothing to do with *post*-incrementing. The same would happen if it was a pre-increment. In either case, it's just the increment part that is the issue. Or rather, it's just the logic if `i = 5` the loop continues, if `i = 6` the loop stops. Hence, why `i` is `6` after the end of the loop. – VLAZ Dec 31 '20 at 10:23
  • @VLAZ you and Simran answered my question, Thanks! – Felipe Briga Dec 31 '20 at 10:32

2 Answers2

2

Basically you're getting the value of i at the termination of the loop where i > 5. To print i: 5 five times:

for(var i = 0; i < 5; i++){
    setTimeout(function(){
        console.log("i: " + i)
    }, i*1000)
}
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

This is because by the time it starts printing values, loop is already completed.

In last iteration(i==5), value of i increases because of i++.

So by the time value is printed, i is updated to value 6 instead of 5.

Simran
  • 98
  • 6