Javascript is a single-thread system. setTimeout
basically puts your request on the call stack to be executed after 1 second.
It is still fired in the scope of your function, but at the end of it, with a 1 second delay.
At the end of your function, i === 3
and because you execute it 3 times, you'll get result === 9
You can see this more clearly if you do this:
var result = 0;
for (var i = 0; i < 3; i++) {
setTimeout(function() {
result += i;
console.log("i: " + i);
console.log("result: " + result)
}, 1000);
}
You can wrap up your timeout, to break the dependency on i
.
Do this by placing setTimeout
in a function and pass i
into it. that way, it doesn't matter what i
is,
as we are using j
which is scoped inside the new function.
var result = 0;
for (var i = 0; i < 3; i++) {
(function(j){
setTimeout(function() {
result += j;
console.log("i: " + i);
console.log("j: " + j);
console.log("result: " + result)
}, 1000);
})(i);
}