Consider this simple example:
var count = 0;
for (var i = 0; i < 4; i++ ) {
setTimeout(function() {
console.log(i, count++);
}, i * 200);
}
which displays the following
4 0
4 1
4 2
4 3
I would suggest that it ialways resolves to 4, because the setTimeout callback closes on variable I, but I cannot figure out why the same is not true for count?
var count = 0;
for (var i = 0; i < 4; i++ ) {
setTimeout(function() {
console.log(i, count++);
}, i * 2000 );
}
Run code
source
share