Skip to content
Advertisement

Interval id counter keeps growing after clearing old one

Suppose I have the following intervals, the id of the first interval is 1, even that I cleared it the second interval gets id of 2. is there a way the I can reset the interval’s id when it cleared? such that the second interval will have id of 1.

let it=setInterval(function(){
console.log(it);// prints 1
},1000);

clearInterval(1);

let it2=setInterval(function(){
console.log(it2); // prints 2
},1000);

Advertisement

Answer

…is there a way the I can reset the interval’s id when it cleared?

No. Every time you call setInterval or setTimeout, a new handle value is created. This is per specification. The only thing you can rely on about the handle is that, in the browser environment, it will be a whole number greater than 0 and won’t be the same as any other timer handle that’s been provided by previous calls in the same realm (roughly, on that page). (On Node.js it’s not a number, it’s an object.) (The fact it’s never 0 is handy; you can use 0 as a “no timer is set” value for the handle variable.)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement