Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 420
user3719454 Avatar asked Oct 23 '15 14:10

user3719454


People also ask

Can I call clearInterval inside setInterval?

Conclusion. To clear this setInterval inside a function with JavaScript, we can call the clearInterval function.

Does clearInterval stop immediately?

I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued.

Is setInterval called immediately?

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.


1 Answers

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)

like image 109
James Thorpe Avatar answered Oct 08 '22 17:10

James Thorpe