3

I've written a function that changes the css positioning of a div

I've been successfully using setTimeout to call the function at a specific interval

NOW what I'm trying to do is call the function on 28 different divs on the same page, each with its own speed.

my thinking was that I could do this with a for loop like so:

for (var x = 0; x < 28; x++)
   { setInterval(function(){changeDirection(divlist[x])}, divs[divlist[x]].speed);}

using the object 'divs' 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 so...

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...

does anyone have any idea why? and is there a way to call setInterval on many different functions with a loop like this

pepperdreamteam
  • 2,772
  • 3
  • 17
  • 15
  • possible duplicate of [setTimeout in a for-loop and pass i as value](http://stackoverflow.com/questions/5226285/settimeout-in-a-for-loop-and-pass-i-as-value) – Bergi Aug 29 '12 at 16:00

3 Answers3

4

You need to "anchor" the value of your loop iterator, otherwise it keeps incrementing and all the intervals affect the 29th one, 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 really bad idea. Consider rewriting your code so that you only have one interval that calculates the new positions based on the speed value.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

My approach to these self calling functions.

var i = -1;
(function cssPositioning() {
  i++;
  if ( i < 28 ) {
            changeDirection(divlist[i]);
    setInterval(cssPositioning, divs[divlist[i]].speed);
  }
})();
mikevoermans
  • 3,967
  • 22
  • 27
1

Based on @Kolink's explanation, you can try

for (var x = 0; x < 28; x++){ 
   setInterval(function(){
     var local = x;  //anchor the variable  
     changeDirection(divlist[local])}, divs[divlist[local]].speed);
   });
}

Hope this helps.

Wei Ma
  • 3,125
  • 6
  • 44
  • 72