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));
...
}
When the loop is executed more than once, the
timeouts[i]
value surpasses the value of loop's index: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 loopi
value only 3, so I never can clear the 3rd(nor any) setTimeout intended to be saved:clearTimeout(timeouts[i]);