Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing timer value with clearInterval before initializing the timer

while googling for some content i found this code.

clearInterval(slip.timer);    
slip.timer = setInterval(function () { mv(target, direction); }, 15);

My doubt is first we need to set timer with setInterval then clear it with clearInterval.Here how can we use slip.timer even before it's initialization? can anyone help me? In which applications do we code like this?


1 Answers

So long as slip is initialised by the time this code runs, it is fine. Calling clearInterval with a value that's not a valid interval ID (eg undefined or null if slip.timer not been set yet) is defined behaviour, as per the spec:

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowTimers object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does not identify an entry in the list of active timers of the WindowTimers object on which the method was invoked, the method does nothing.)

(emphasis mine)

This is a fairly common approach when the timer could be triggered several times to ensure you don't have multiple copies of the interval timer calling your callback - if there's a chance it's going to happen, you want to make sure you clear the previous interval before starting a new one.

like image 57
James Thorpe Avatar answered Feb 21 '26 17:02

James Thorpe