Say
for (var i = 0; i < 3; ++i) {
var iteration = i;
setTimeout(function() { console.log(iteration); }, i*1000);
}
I thought the above function would log as 0,1,2. But it logs out 2,2,2. Can anyone helps me to explain?
Say
for (var i = 0; i < 3; ++i) {
var iteration = i;
setTimeout(function() { console.log(iteration); }, i*1000);
}
I thought the above function would log as 0,1,2. But it logs out 2,2,2. Can anyone helps me to explain?
The three iterations of your loop run all at once, and you're scheduling the callback of setTimeout()
to occur in the future.
By the time they run, i
already has the value of 2
.
In other words, setTimeout()
doesn't block the loop.