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 10.
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 < 10; i++) {
(function (x) {
setTimeout(function () { alert(x); }, 0);
})(i);
}
Войдите чтобы поставить Нравится
Войдите чтобы прокомментировать