This is the piece of code,which on execution gives 6,five times in one second intervals. Can someone please explain this to me in detail?
for (var i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}
This is the piece of code,which on execution gives 6,five times in one second intervals. Can someone please explain this to me in detail?
for (var i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}
The variable i
is part of the closure of the timer
function.
When the timer
function is executed,
it will print the value of i
at that time.
By the time that happens, the loop has already completed,
and so the value of i
is 6.
For all 5 executions of timer
,
so you see 6 printed 5 times.
What else would you expect?
If you want to print a count from 1, 2, ..., 5 with timeouts in between,
then pass the current concrete value of i
into the closure,
using an immediately evaluated function expression:
for (var i = 1; i <= 5; i++) {
setTimeout(function (value) {
return function timer() {
console.log(value);
}
}(i), i*1000);
}
Another equivalent variation:
for (var i = 1; i <= 5; i++) {
(function () {
var value = i;
setTimeout(function timer() {
console.log(value);
}, i*1000);
})()
}
Notice in both examples that the variable value
is defined in the closure of the inner function, and a different instance of value
is created in every iteration of the for
loop,
with the value of i
at the time of the iteration.
This is the crucial difference from the code in the question.