I have a very trivial question. For a simple loop with setTimeout, like this:
for (var count = 0; count < 3; count++) {
setTimeout(function() {
This is to do with closure scoping. The same variable count
is available in the scope for each of the setTimeout callback functions. You are incrementing its value and creating a function, but each instance of the function has the same variable count
in its scope, and by the time the callback functions execute it will have the value 3.
You need to create a copy of the variable (e.g. var localCount = count
) inside a new scope in the for
loop to make this work. As for
doesn't create a scope (which is the cause of the whole thing) you need to introduce one with a function scope.
e.g.
for (var i = 0; i < 5; i++) {
(function() {
var j = i;
setTimeout(function() {
console.log(j)
},
j*100);
})();
}