setTimeout 在 setInterval 中不起作用



我正在构建一个chrome插件在manifest v2。我有一个每分钟运行一次的间歇。在它里面,我有一个函数,应该重新加载页面将重新加载每3分钟,如果布尔值为假。如果为true,则3分钟的计时器需要自行复位。

由于某种原因,当我设置计时器并记录它时,它被卡在'1'。只有当我不断地设置它时,它才会移动-理论上应该重置它,但没有-它只是继续。

当我调用clearartimeout时,什么都没有发生——计时器保持不变。即使我尝试将timer变量设置为null,它仍然会有规律地继续。

这是代码,希望你能帮我弄清楚:

var timerLoop = [].
var audioPlayed = false;
var timer = null;
function clearTimerLoop(){
for ( var i = 0; i < timerLoop.length; ++i ){
clearTimeout( timerLoop[i] );
timerLoop[i] = null; //Tried here to make it a null, no success
}
timerLoop = []; //Tried here to remove everything from the array, no success
console.log("Timer cleared");
}
function startTimer(){
timer = window.setTimeout(refreshPage, 180000); /* reload every 3 minutes */
timerLoop.push(timer);
console.log("Timer created");
}
loopInterval = setInterval(function(){loopChecker();}, 60000);
function loopChecker(){
if(audioPlayed){
clearTimerLoop()
timer = null;
audioPlayed = false;
}

if(!audioPlayed && timer == null){
startTimer();
console.log("Refresh timer running (" + timerLoop[0] + ")");

}        
console.log(timer);
}

提前感谢。

正如你所看到的,我正在重置定时器尽可能多,但什么也没有发生。此外,计时器被卡在1,除非我再次设置它在每个定时器loopChecker()运行,并再次-这应该重置它,但它继续。我想也许每次运行都会设置一个新的计时器,所以我创建了一个数组,每次创建时都会推送计时器,然后当我想要清除时,每个计时器都会被清除。没有帮助。

不需要这么做,你可以这样做:

timer = null
if (boolean == false) {
timer = setInterval(() => {
window.location.reload();
}, 180000)
...
}
else {
clearInterval(timer);
timer = null; // stops page reloading every 3 min by deleting setInterval and its callback
...
}

最新更新