Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to call clearInterval inside a setInterval handler?

I have a piece of Javascript that checks for a condition (via an AJAX call) every n seconds. If that condition is true, it stops checking. I have implemented it in the following way:

var stopTimer; var timerId = setInterval(function() {      /* Make Ajax Calls and set stopTimer */      if (stopTimer) {         clearInterval(timerId);     } }, 10000); 

However, I find erratic behaviour: Works sometimes, but at other times, it keeps checking forever. I have checked that (as much as is possible) there is no error in any part of the code.

I am therefore suspecting that calling clearInterval inside a setInterval handler might be the culprit. Is that right? Is it OK to call clearInterval inside a setInterval handler?

Thank you for your attention

like image 658
Ya. Perelman Avatar asked Mar 16 '10 04:03

Ya. Perelman


People also ask

Can you use clearInterval inside setInterval?

It's worth noting that the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably. However, for clarity, you should avoid doing so.

When should I use clearInterval?

The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that. setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms). setInterval() executes the passed function for the given time interval.

How do I call API in setInterval?

Using setInterval() We can pass an API call inside the setInterval() to make it run repeatedly. const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); }, 2000); Once this interval is created, it will send the API request after every two seconds.

What is the difference between clearTimeout and clearInterval?

The clearTimeout() method clears the time out that has been previously set by the setTimeout() function. The clearInterval() method clears the interval which has been previously set by the setInterval() function.


1 Answers

It's safe. The issue is probably to do with stopTimer not being set as you expect.

like image 198
SpliFF Avatar answered Oct 18 '22 15:10

SpliFF