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)
}
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)
}
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)
}
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.