如何从 setInterval 退出

如果条件正确,我需要从运行间隔中退出:

var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
<--- exit from the loop--->
}
}, 10000);
112636 次浏览

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.

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>