How to save/clear setTimeout's array using loop's index?

可紊 提交于 2020-01-17 04:59:25

问题


I am calling a for loop multiple times. I would like to save a single setTimeout for each index. The idea is to use the loop's index as setTimeout's array index, but setTimeout returns an incremental ID number, I would like to reset it, or override to take control of the returning ID, so I can identify each timeout with a given index, always within the range of loop's index that is executed over and over again. Being able to use clearTimeout later on with a specific index.

var timeouts = [];
for(var i=0; i < 5 ; i++) {
   ...
   (function(delay, timeouts, i){
      // Keeps a reference of the timeout to clear it later.
      timeouts[i] = setTimeout(function() {
         countInView--;
      }, delay);
      console.log("i: "+5+ " | timeout: "+timeouts[i]);
      // i: 5 | timeout: 25 -> Surpasses index, 
      // I'd like to override positions by ID or by index.
   }(delay, timeouts, i));
   ...
}
  1. When the loop is executed more than once, the timeouts[i] value surpasses the value of loop's index:

  2. I just want to clear the timeout in other part of the code, but when reaching this part of the code, the value of timeouts[i] may be 140, and loop i value only 3, so I never can clear the 3rd(nor any) setTimeout intended to be saved:

    clearTimeout(timeouts[i]);
    

回答1:


You could use 2 dimensional array for this, first dimension will change along with the for loop index, whilst second dimension could remain in 0 to take control of the assigned timeout's IDs for each iteration.

For saving setTimeout within a index in a loop

var timeouts = []; // Two  dimensional array
for (i = 0; i < 5; i++)  
    timeouts[i] = [];

for(var i=0; i < 5 ; i++) {
    ...
    (function(delay, $element, savedtimeout){
        savedtimeout[0] = setTimeout(function() {
            countInView--;
        }, delay, savedtimeout);
    }(delay, $element, timeouts[i]));
    ...
}

For clear setTimeout within a index in a loop

if(timeouts[i][0] != null) {
    //Removes the timeout from the queue
    clearTimeout(timeouts[i][0]);
}


来源:https://stackoverflow.com/questions/37497872/how-to-save-clear-settimeouts-array-using-loops-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!