清除未定义变量的间隔问题原因



这是我的代码(在button.click()函数内(

if(inBreak === true) {
inBreak = false;
var timer = setInterval(function() {
if(seconds == 0) {
console.log(minutes);
minutes -= 1;
seconds = 59;
} else {
seconds -= 1;
}
$('.minutes').text(minutes);
$('.seconds').text(seconds);
}, 1000);
} else {
inBreak = true;
console.log(timer);
clearInterval(timer);
}

问题是clearInterval(timer)不起作用,因为没有定义计时器,但我在第一次单击(并使用该功能(时定义了它。

那么你有实现它的想法吗? 我尝试让/常量代替var,但无论如何都不起作用:(

timer

是一个局部变量,它在函数的末尾被破坏。

将其存储在其他地方(例如作为全局变量(:

window.myTimer = setInterval(function() {
....
clearInterval(window.myTimer);

我怀疑您正在click处理程序中声明timer变量,因此在每次click,变量timer都会被重置

例如

function() { // event handler function
var timer;
if(inBreak === true) {
// code
timer = setInterval()
} else {
// code 
console.log(timer);
}
}

应在事件处理程序范围之外创建一个变量,以便该变量可用并共享相同的引用。

例如

var timer; // <- Move the declaration outside the function scope to be available and share same reference.
function() { // event handler function
if(inBreak === true) {
// code
timer = setInterval()
} else {
// code 
console.log(timer);
}
}

最新更新