Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from setInterval

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); 
like image 309
Martin Ongtangco Avatar asked Nov 25 '09 06:11

Martin Ongtangco


People also ask

How do I leave setInterval?

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.

How do you stop setInterval from inside?

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() .

How do you stop an interval in a for loop?

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);


2 Answers

Use clearInterval:

var refreshId = setInterval(function() {   var properID = CheckReload();   if (properID > 0) {     clearInterval(refreshId);   } }, 10000); 
like image 184
Christian C. Salvadó Avatar answered Oct 13 '22 14:10

Christian C. Salvadó


Pass the value of setInterval to clearInterval.

const interval = setInterval(() => {   clearInterval(interval); }, 1000) 

Demo

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>
like image 25
Tobias Goulden Schultz Avatar answered Oct 13 '22 14:10

Tobias Goulden Schultz