Calling setTimeout with a for loop
I wrote a function that changes the css positioning of a div
I have successfully used setTimeout to call a function at a specific interval
NOW what I'm trying to do is call a function on 28 different divs on the same page, each at a different speed.
I thought I could do it with a for loop like so:
for (var x = 0; x < 28; x++)
{ setInterval(function(){changeDirection(divlist[x])}, divs[divlist[x]].speed);}
using the "divs" object where the speed and id are stored
The only way I could get them all to move against the timer was to call setInterval 28 times like this ...
setInterval(function(){changeDirection(divlist[1])}, divs[divlist[1]].speed);
setInterval(function(){changeDirection(divlist[2])}, divs[divlist[2]].speed);
setInterval(function(){changeDirection(divlist[3])}, divs[divlist[3]].speed);
setInterval(function(){changeDirection(divlist[4])}, divs[divlist[4]].speed);....etc
the for loop did NOT work ...
Can anyone understand why? and is there a way to call setInterval on many different functions with a loop like this
source to share
You need to "bind" the value of your loop iterator, otherwise it keeps increasing and all the intervals affect the 29th which doesn't exist.
for(var x=0; x<28; x++) {
(function(x) {
// code goes here
})(x);
}
However, 28 timers on one page is a very bad idea. Consider rewriting the code so that you only have one interval that calculates new positions based on the speed value.
source to share