How to use setInterval function within for loop

前端 未结 6 1027
攒了一身酷
攒了一身酷 2020-11-27 16:00

I\'m trying to run multiple timers given a variable list of items. The code looks something like this:

var list = Array(...);

for(var x in list){
    setInt         


        
6条回答
  •  一个人的身影
    2020-11-27 16:50

    So, a few things:

    1. Most importantly, the callback function you've passed to setInterval() maintains a reference to x rather than the snapshot value of x as it existed during each particular iteration. So, as x is changed in the loop, it's updated within each of the callback functions as well.
    2. Additionally, for...in is used to enumerate object properties and can behave unexpectedly when used on arrays.
    3. What's more, I suspect you really want setTimeout() rather than setInterval().

    You can pass arguments to your callback function by supplying additional arguments to setTimout():

    var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

    Numbers will be passed by value rather than reference. Here's an example:

    var list = [1,2,3,4];
    
    for (var x = 0, ln = list.length; x < ln; x++) {
      setTimeout(function(y) {    
        console.log("%d => %d", y, list[y] += 10);
      }, x * 500, x); // we're passing x
    }

提交回复
热议问题