如果条件正确,我需要退出运行间隔:
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
<--- exit from the loop--->
}
}, 10000);
答案 0 :(得分:118)
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
clearInterval(refreshId);
}
}, 10000);
答案 1 :(得分:1)
您可以设置变量的作用域,以避免污染名称空间:
const CheckReload = (() => {
let counter = - 5;
return () => {
counter++;
return counter;
};
})();
{
const refreshId = setInterval(
() => {
const properID = CheckReload();
console.log(properID);
if (properID > 0) {
clearInterval(refreshId);
}
},
100
);
}
答案 2 :(得分:0)
将setInterval
的值传递给clearInterval。
const interval = setInterval(() => {
clearInterval(interval);
}, 1000)
计时器每秒钟递减,直到达到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>
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>