for (var i = 1; i <= 3; ++i) {
setTimeout((function (x) {
return function () { alert(x); }
})(i), i * 1000);
}
deceze
2010-10-28 01:57:22
for (var i = 1; i <= 3; ++i) {
setTimeout((function (x) {
return function () { alert(x); }
})(i), i * 1000);
}
That is a very common issue. With JS 1.7 this is easily solved using let
keyword. To check browser version equivalency click here.
You can workaround this using closures. Create a scope for i
and return the function for setTimeout
.
for (var i = 1; i <= 3; ++i) {
setTimeout((function(i) { /* i is now a parameter */
return function () { /* this function is the one that will execute */
alert(i); /* this `i` is not the same as the one used on the loop */
}
})(i), i * 1000);
}