Javascript has function scope. This means that
for(...) {
var j = i;
}
is equivalent to
var j;
for(...) {
j = i;
}
In fact, this is how Javascript compilers will actually treat this code. And, of course, this causes your little "trick" to fail, because j
will be incremented before the function in setTimeout
gets called, i.e. j
now doesn't really do anything different than i
, it's just an alias with the same scope.
If Javascript were to have block scope, your trick would work, because j
would be a new variable within every iteration.
What you need to do is create a new scope:
for(var i = ...) {
(function (j) {
// you can safely use j here now
setTimeout(...);
})(i);
}
No comments:
Post a Comment