In your loop, i starts at 0 and iterates until it's equal to 3. That means that whenever you access i after the loop has finished running (for example, in a listener function) it will be equal to 3. You can see this in the following code:
for(var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
That will print all 5s because the function is being called after the loop has finished iterating.
Edit: To fix the issue, you can use javascript's hip new declaration statements: let and const. They exist only in the scope that they are declared, and their values are therefore not overwritten.
for(var i = 0; i < 5; i++) {
const j = i;
setTimeout(function() {
console.log(j);
}, 1000);
}
Edit 2: Replacing var i
with let i
appears to work as well:
for(let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
Edit 3: If es6 isn't an option, you could bind i's value to the function:
for(var i = 0; i < 5; i++) {
setTimeout((function(j) {
console.log(j);
}).bind(null, i), 1000);
}