The function argument to setTimeout
is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i
, which is 3
.
Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:
for (var i = 1; i <= 2; i++) {
(function (x) {
setTimeout(function () { alert(x); }, 100);
})(i);
}