Is it possible to call clearInterval () before setInterval ()?

I have the following code snippet:

if (someCondition) { // clear globTimer first?? globTimer = setInterval(function() { someBlinkingCode; }, 1000); } else { clearInterval(globTimer); } 

but this part of the code can be called several times, where someCondition will be true. This means that several intervals will be created, and not all of them will be destroyed. And after a while, the blink was more frequent than 1 second, so I added clearInterval(globTimer); instead of a comment. This change solved my problem, but is this solution ok? Can I call clearInterval() more than once for the same variable or call it for undefined ?

+5
source share
1 answer

Yes, it’s normal to call clearInterval (and clearTimeout ) with "invalid" identifiers. The specification says:

The clearInterval () method should clear the record identified as a descriptor from the list of active intervals of the WindowTimers object on which the method was called, where handle is the argument passed to the method, if any. ( If the handle does not identify the entry in the list of active intervals of the WindowTimers object on which the method was called, the method does nothing. )

(Emphasis mine)

+7
source

Source: https://habr.com/ru/post/1234374/


All Articles