calling setTimeout with a for loop

前端 未结 3 1714
遇见更好的自我
遇见更好的自我 2021-01-21 00:25

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

相关标签:
3条回答
  • 2021-01-21 00:29

    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.

    0 讨论(0)
  • 2021-01-21 00:33

    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);
      }
    })();
    
    0 讨论(0)
  • 2021-01-21 00:38

    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.

    0 讨论(0)
提交回复
热议问题