You can't name your own timeouts. setTimeout
and setInterval
return a numeric ID, which is what must be passed into clearTimetout
. You can, however, use an array or an object to store your timeouts:
var timeoutIds = [];
for(var i=0; i<5; i++){
timeoutIds.push(setTimeout(function(){ /* ... */ }));
}
Or, if you need to name them, you can do it like this:
var timeoutIds = {};
for(var i=0; i<5; i++){
timeoutIds['timeout_' + i] = setTimeout(function(){ /* ... */ });
}
You should also be aware that in your loop, as you've written it, all the timeouts will print '4 timeout called'; that's because the functions are declared in a closure that contains i
, and by the time they get around to executing, the loop will have finished, and have the final value 4 (unless it's re-used by other code in the same scope, of course). What you probably want to do is this:
var timeoutIds = [];
for(var i=0; i<5; i++){
timeoutIds.push(
(function(i){
// i now captured as a function-scope variable
return setTimeout(function(){ console.log(i + ' timeout called'); });
})(i)
);
}
This creates an immediately-invoked function expression (IIFE), which "captures" the value of i
as a function-scope variable.