I have a following fragment of code:
if (someCondition) {
// clear globTimer first??
globTimer = setInterval(function() {
someBlinkingCode;
}, 1000);
} else {
clearInterval(globTimer);
}
but this part of code can be called multiple times where someCondition
will be true. It means multiple intervals will be created and not all of them will be destroyed. And after a certain time blinking was more frequent than 1 sec so I added clearInterval(globTimer);
instead of the comment. This change solved my problem but is this solution okay? Is it okay to call clearInterval()
more times for the same variable or call it for undefined
?
Conclusion. To clear this setInterval inside a function with JavaScript, we can call the clearInterval function.
I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued.
The setInterval() method always invokes the function after the delay for the first time using two approaches: Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function.
Yes, it's fine to call clearInterval
(and clearTimeout
) with "invalid" identifiers. The specification says:
The clearInterval() method must clear the entry identified as handle from the list of active intervals of the WindowTimers object on which the method was invoked, where handle is the argument passed to the method, if any. (If handle does not identify an entry in the list of active intervals of the WindowTimers object on which the method was invoked, the method does nothing.)
(Emphasis mine)
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