Reputation:
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?
Upvotes: 3
Views: 1955
Reputation: 19485
It’s useful to clear a setTimeout
or a setInterval
before starting a new one if those timers are being used multiple times.
Consider this example: you have a stop watch that starts from 0. You start it and the numbers increase. Now you want to reset the stop watch and still have it running (e. g. noting the time of a completed lap). You could have a single function that does the following to accomplish this:
setInterval
If you ran this function twice — i. e. one initial start and then a reset — , there would be two interval timers set as opposed to one. Thus the stop watch will run twice as fast. This is undesired behavior and therefore the function should instead do these steps:
clearInterval
if there is onesetInterval
As James Thorpe pointed out, an undefined
or null
reference passed to clearInterval
is not a big deal.
If you want to be safe about clearing something before it has been intitialized however you can simply intialize that something:
var slip = {
timer: 0
};
// … Later:
clearInterval(slip.timer);
Or you could test whether that something exists:
if(window.slip && slip.timer){
clearInterval(slip.timer);
}
Or if your code is in a closure and slip
isn’t defined globally:
if(typeof slip !== "undefined" && slip.timer){
clearInterval(slip.timer);
}
Upvotes: 0
Reputation: 32202
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.
Upvotes: 6