为什么 'setInterval()' 呼叫没有停止?
Why doesn't the 'setInterval()' call stop?
我已经查看了有关此主题的其他 SO 问题并尝试了解决方案。我找不到错误。所以我想,这一定是一个明显的错误。任何帮助将不胜感激。
var interval = 0;
function repeat(time, bool) {
var interval = setInterval(choose, time * 1000);
function stopRepeat () {
console.log("im trying to stop");
clearInterval(interval);
}
if (bool) {
stopRepeat();
}
}
正在记录 "im trying to stop"。所以这意味着 clearInterval()
是不起作用的。我也曾尝试将其命名为 window.interval,但这并没有什么不同。
我还记录了它应该清除后的时间间隔,它只是产生相同的时间间隔而不是清除的时间间隔。
谢谢!
所以我要先用注释分析你的代码。
/*
* First this declaration (var interval=0) is redundant as it is re-declared in the
* repeat function
*/
var interval = 0;
function repeat(time, bool) {
var interval = setInterval(choose, time * 1000);
function stopRepeat () {
console.log("im trying to stop");
clearInterval(interval);
}
/*
* Lets assume bool is true.
* StopRepeat is called immediately and your interval function never gets
* to execute nor does your choose function even gets called.
* Now lets assume bool is even false.
* StopRepeat never gets called and there is not way of clearing the interval
*/
if (bool) {
stopRepeat();
}
}
有很多方法可以尝试,我会稍微修改一下。
var choose = function(){
console.log("choose was called!");
}
function repeat(time, timesToRun=1) {
var count = 0;
var interval = setInterval(function(){
choose();
if(count===timesToRun/*Or a better condition to stop the interval*/){
console.log("Clearing my intervals");
clearInterval(interval);
}
count++;
}, time * 1000);
}
repeat(5, 2);
我已经查看了有关此主题的其他 SO 问题并尝试了解决方案。我找不到错误。所以我想,这一定是一个明显的错误。任何帮助将不胜感激。
var interval = 0;
function repeat(time, bool) {
var interval = setInterval(choose, time * 1000);
function stopRepeat () {
console.log("im trying to stop");
clearInterval(interval);
}
if (bool) {
stopRepeat();
}
}
正在记录 "im trying to stop"。所以这意味着 clearInterval()
是不起作用的。我也曾尝试将其命名为 window.interval,但这并没有什么不同。
我还记录了它应该清除后的时间间隔,它只是产生相同的时间间隔而不是清除的时间间隔。
谢谢!
所以我要先用注释分析你的代码。
/*
* First this declaration (var interval=0) is redundant as it is re-declared in the
* repeat function
*/
var interval = 0;
function repeat(time, bool) {
var interval = setInterval(choose, time * 1000);
function stopRepeat () {
console.log("im trying to stop");
clearInterval(interval);
}
/*
* Lets assume bool is true.
* StopRepeat is called immediately and your interval function never gets
* to execute nor does your choose function even gets called.
* Now lets assume bool is even false.
* StopRepeat never gets called and there is not way of clearing the interval
*/
if (bool) {
stopRepeat();
}
}
有很多方法可以尝试,我会稍微修改一下。
var choose = function(){
console.log("choose was called!");
}
function repeat(time, timesToRun=1) {
var count = 0;
var interval = setInterval(function(){
choose();
if(count===timesToRun/*Or a better condition to stop the interval*/){
console.log("Clearing my intervals");
clearInterval(interval);
}
count++;
}, time * 1000);
}
repeat(5, 2);