Reputation:
I'm new to learning javascript and getting strange behaviour that I don't understand
So this is printing exactly what I expect. 0,1,2,3,4
var numberOfPlayers = 5;
for ( i = 0; i < numberOfPlayers; i++ ) {
alert(i);
}
But when I try the following code where I want to run a function every 1 seconds I get, 5,5,5,5,5
var numberOfPlayers = 5;
for ( i = 0; i < numberOfPlayers; i++ ) {
setInterval(function () {
alert(i);
}, 1000);
}
Can anyone explain to me what is actually happening here. I would expect the same numbers in both parts of code.
Upvotes: 0
Views: 131
Reputation: 12419
As @Quentin explained in his answer, it's an issue of timing and because of the closure inside of setInterval()
. There's a good explanation here: Javascript infamous Loop issue?.
For a case like this I would probably use the code @Soren suggested. Another option would be to use a separate function:
var numberOfPlayers = 5;
for ( i = 0; i < numberOfPlayers; i++ ) {
intervalAlert(i);
}
function intervalAlert(i) {
setInterval(function () {
alert(i);
}, 1000);
}
See also http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops/
Upvotes: 0
Reputation: 14688
The I is not bound in the inner function inside the loop -- to something like this to bind it in each iteration of the loop
var numberOfPlayers = 5;
for ( i = 0; i < numberOfPlayers; i++ ) {
(function(i) {
setInterval(function () {
alert(i);
}, 1000);
})(i);
}
Upvotes: 1
Reputation: 52
You should be getting 5 5 5 5 5. The reason is that your for loop very quickly runs and binds the function to run 5 times. It iterates through itself until i is equal to 5. By the time the second is up and the function is scheduled to run, i is equal to 5. It will then repeat every 1 second 5 times.
Upvotes: 0
Reputation: 943517
In the first instance, you alert the value of i
as it goes around the loop.
In the second, you alert the value of i
after one second. By the time that second has passed, the loop has finished going around five times, so the value of i
at the time is the last value of i
.
Upvotes: 2