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
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.
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.
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.
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.
It's safe. The issue is probably to do with stopTimer not being set as you expect.
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