我正在尝试创建一个简单的倒计时器,一旦遇到虚假条件,它就会动态停止。 (在倒计时应该停止时为演示实现 setTimeout)
我通常不使用 setInterval/clearInterval
东西,所以我研究并尝试了一些我发现的东西,但仍然不起作用。
我相信这里只有很少的差异。
这是代码。
var intervals;
function startTimer(isStarted) {
intervals = setInterval(_countDown, 1000);
var requestTimer = 60,
seconds;
function _countDown() {
seconds = parseInt(requestTimer % 60, 10);
seconds = seconds < 10 ? "0" + seconds : seconds;
console.log(seconds);
if (--requestTimer < 0) {
requestTimer = 60;
}
}
if (!isStarted) {
console.log("timer now should stop!!!!!!");
clearInterval(intervals);
}
}
startTimer(true);
setTimeout(startTimer, 3000);
<h1>Open the console to see the timer.</h1>
最佳答案
自从您调用 startTimer-method 两次(最后两行代码)以来,您实际上启动了两次间隔。这就是为什么单个clearTimeout 不再能解决问题的原因。您还可以在声明要执行的函数之前设置时间间隔。所以我会像这样简化事情:
var interval;
function startTimer() {
var requestTimer = 60,
seconds;
function _countDown() {
seconds = parseInt(requestTimer % 60, 10);
seconds = seconds < 10 ? "0" + seconds : seconds;
console.log(seconds);
if (--requestTimer < 0) {
requestTimer = 60;
}
}
interval = setInterval(_countDown, 1000);
}
startTimer();
setTimeout(function() {
console.log("timer now should stop!!!!!!");
clearTimeout(interval);
}, 3000);
关于javascript - 清除间隔在函数的 if 语句内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37158166/