问题描述
有一个使用 setInterval()
设置间隔的函数,但即使在调用 clearInterval()
之后,我也可以在控制台中看到 else
条件仍在运行.如何正确清除该间隔?
There is a function which sets an interval using setInterval()
, but even after calling clearInterval()
, I can see in the console that the else
condition is still running. How can I clear that interval properly?
function increase(old, step, neu) {
var i = 0;
var delay2;
function countUp() {
if (i < 5) {
old += step;
// console.log("increase")
$("#total-price-value").text(old + " dollors");
$("#total-price-value").digits();
i++;
delay2 = setInterval(countUp, 80);
} else {
clearInterval(delay2);
console.log(delay2);
}
}
countUp();
}
推荐答案
您似乎对超时和间隔之间的区别有些困惑.超时仅触发一次;间隔多次触发.如果您使用间隔,您可能只想设置一次(您每次都设置它).如果您使用超时,您可能希望每次都设置它(就像您正在做的那样).
It looks like you're a little confused about the difference between timeouts and intervals. Timeouts fire only once; intervals fire many times. If you're using an interval, you probably only want to set it once (you're setting it every time). If you're using a timeout, you probably want to set it every time (like you're doing).
为了解决这个问题,您要么想切换到超时(可能是最简单的;只是搜索/替换),要么只设置一次间隔.
In order to fix the problem, you'll either want to switch to timeouts (probably the easiest; just a search/replace) or only set the interval once.
例如,以下是如何使用 setTimeout
计数到 5:
For example, here is how one might use setTimeout
to count up to five:
var count = 0;
function timeoutFired() {
count++;
if(count < 5) {
setTimeout(timeoutFired, 1000);
}
}
setTimeout(timeoutFired, 1000);
使用超时,我们不需要清除来阻止它计数;简单地不设置超时将阻止它再次运行.
Using timeouts, we don't need to clear to stop it from counting; simply not setting a timeout will prevent it from running again.
以下是如何使用 setInterval
:
var count = 0;
function intervalFired() {
count++;
if(count >= 5) {
clearInterval(interval);
}
}
var interval = setInterval(intervalFired, 1000);
如果您希望某些使用间隔定期运行的代码停止,您必须调用 clearInterval
.请注意,我们只调用 setInterval
一次,而 setTimeout
每次我们不希望它继续.
If you want some code running periodically using intervals to stop, you must call clearInterval
. Note that we only call setInterval
once, versus setTimeout
every time we didn't want it to continue.
这篇关于为什么 clearInterval 在这段代码中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!