Rectangle 27 0

javascript How to saveclear setTimeout's array using loop's index?


if(timeouts[i][0] != null) {
    //Removes the timeout from the queue
    clearTimeout(timeouts[i][0]);
}
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]));
    ...
}

@Pa If the 1st time loop executes I trigger only 3 delayed actions for 1minute delay, the 2nd time loop executes, I want to remove 2, I will be already on second dimension(or maybe 3rd), and I will only not be able to remove the past setTimeouts, but also I will be creating a second timeout for the same iteration. I only want to save a single setTimeout per iteration, in the example I am trying to save 5, but in future iterations I want to be able to clear the same index that was saved previously, if a condition occurs. Sorry if I misunderstood, (still you're not using push).

@Roizpi : Then you can clearTimeout(timeouts[0][0]) //so it will clear first timeout of first iteration

@Roizpi: Does this update approach help you, where I have maintained 2 dimensional array for time outs...

Thank you, is like all examples I have seen so far using this. But I have never seen someone removing it with a given index. I'd like to clear a specific position in the array of setTimeout, rather than using pop() or shift().

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.

Note