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);
Use clearInterval:
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
clearInterval(refreshId);
}
}, 10000);
Updated for ES6
You can scope the variable to avoid polluting the namespace:
const CheckReload = (() => {
let counter = - 5;
return () => {
counter++;
return counter;
};
})();
{
const refreshId = setInterval(
() => {
const properID = CheckReload();
console.log(properID);
if (properID > 0) {
clearInterval(refreshId);
}
},
100
);
}
Pass the value of setInterval to clearInterval.
Simple example
const interval = setInterval(() => {
clearInterval(interval);
}, 1000)
Countdown example
The timer is decremented every second, until reaching 0.
let secondsToCountDown = 2
const interval = setInterval(() => {
// just for presentation
document.querySelector('.timer').innerHTML = secondsToCountDown
if (secondsToCountDown === 0) {
clearInterval(interval); // time is up
}
secondsToWait--;
}, 1000);
<p class="timer"></p>
Countdown example with separation
let secondsToCountDown = 2
const doStuffOnInterval = () => {
document.querySelector('.timer').innerHTML = secondsToCountDown
if (secondsToCountDown === 0) {
stopInterval()
}
secondsToCountDown--;
}
const stopInterval = () => {
clearInterval(interval);
}
const interval = setInterval(doStuffOnInterval, 1000);
<p class="timer"></p>
来源:https://stackoverflow.com/questions/1795100/how-to-exit-from-setinterval