The setTimeout
callback functions are executed asynchronously, all the console.log
calls you make refer to the same i
variable, and at the time they are executed, the for loop has ended and i
contains 4.
You could wrap your inner setTimeout
call inside a function accepting a parameter in order to store a reference to all the i
values that are being iterated, something like this:
setTimeout(function() {
for (var i = 0; i < 5; i++) {
(function (j) { // added a closure to store a reference to 'i' values
setTimeout(function() {
console.log(j);
}, j * 200);
})(i); // automatically call the function and pass the value
}
}, 200);
Check my answer to the following question for more details: