Roizpi Roizpi - 4 months ago 8x
Javascript Question

Using loop index to reference a setTimeout's array

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() {
}, 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
    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
    may be 140, and loop
    value only 3, so I never can clear the 3rd(nor any) setTimeout intended to be saved:



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() {
        }, 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