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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With