I have a for loop, and I would like to save a setTimeout for each iteration, using the loop's index as setTimeout's array index, so that I am able to use clearTimeout later on with an specific index.
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);
}(delay, timeouts, i));
...
}
-
I don't understand why, when logging the value of
timeouts[i]after assign, its value correspond with an integer number, instead of an object reference of the setTimeout.... (function(delay, timeouts, i){ timeouts[i] = setTimeout(function() { countInView--; }, delay); console.log("value is: "+timeouts[i]); // value is: 5 -> Is an integer, // not an object reference }(delay, timeouts, i)); ... -
When the loop is executed more than once, the
timeouts[i]value surpasses the value of loop's index:// 5th time executing this loop for(i = 0 ; i < 5 ; i++) { ... (function(delay, timeouts, i){ timeouts[i] = setTimeout(function() { countInView--; }, delay); console.log("i: "+5+ " | timeout: "+timeouts[i]); // i: 5 | timeout: 25 -> Surpasses index, // as if it couldn't overwrite positions. }(delay, timeouts, i)); ... } -
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 loopivalue only 3, so I never can clear the 3rd setTimeout intended to be saved:clearTimeout(timeouts[i]);
