I need to exit from a running interval if the conditions are correct:
var refreshId = setInterval(function() { var properID = CheckReload(); if (properID > 0) { <--- exit from the loop---> } }, 10000);
Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.
Stop setInterval() Using clearInterval() Function in JavaScript. The setInterval() function is used to call a function or execute a piece of code multiple times after a fixed time delay. This method returns an id that can be used later to clear or stop the interval using clearInterval() .
Stopping the Function The setInterval() returns a variable called an interval ID. You can then use it to call the clearInterval() function, as it's required by the syntax: clearInterval(intervalId);
Use clearInterval:
var refreshId = setInterval(function() { var properID = CheckReload(); if (properID > 0) { clearInterval(refreshId); } }, 10000);
Pass the value of setInterval
to clearInterval.
const interval = setInterval(() => { clearInterval(interval); }, 1000)
The timer is decremented every second, until reaching 0.
let secondsRemaining = 10 const interval = setInterval(() => { // just for presentation document.querySelector('p').innerHTML = secondsRemaining // time is up if (secondsRemaining === 0) { clearInterval(interval); } secondsRemaining--; }, 1000);
<p></p>
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