The following alerts 2
every time.
function timer() {
for (var i = 0; i < 3; ++i) {
var j = i;
setTimeout(function () {
alert(j);
}, 1000);
}
}
timer();
Shouldn't var j = i;
set the j
into the individual scope of the setTimeout?
Whereas if I do this:
function timer() {
for (var i = 0; i < 3; ++i) {
(function (j) {
setTimeout(function () {
alert(j);
}, 1000);
})(i);
}
}
timer();
It alerts 0
, 1
, 2
like it should.
Is there something I am missing?