Consider this simple example:
var count = 0;
for (var i = 0; i < 4; i++ ) {
setTimeout(function() {
console.log(i, count++);
}, i * 200);
}
which outputs the following
4 0
4 1
4 2
4 3
I would guess that i
always resolves to 4 because the setTimeout callback closes over the variable I but I can't figure out why the same doesn't hold true for count
?
var count = 0;
for (var i = 0; i < 4; i++ ) {
setTimeout(function() {
console.log(i, count++);
}, i * 2000 );
}
The variable i
is incremented by your for
loop, and ends up with the value 4
before any of the timeout handlers run. The variable count
, on the other hand, is only incremented inside the timeout handlers. When the first timeout handler fires, count
will still be 0
.
As the lads before me said, It's because the loop completes before the timeout is activated.
One way around this would be to put your timeout in a different function, and pass the i
to it from within the loop. This ensures that for each iteration, the function is passed the correct i
This is also why count
is set to the expected value; it lies outside of the loop's scope.
for (var i = 0; i < 4; i++) {
doSomething(i);
};
function doSomething(i) {
setTimeout(function() {
console.log(i);
}, i * 2000);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With