我正在尝试将 play/pause
按钮添加到一个计时器,该计时器具有根据 isRunning 的值决定要做什么的功能。第二次单击我的按钮而不是暂停时,计时器似乎添加了另一个 setTimeout
,我不明白为什么。
var isRunning = false;
function start() {
if(isRunning == false) {
isRunning = true;
setInterval(time, 1000);
document.getElementById("play").className = "fa fa-pause";
}
else if(isRunning == true) {
isRunning = false;
document.getElementById("play").className = "fa fa-play";
console.log(isRunning);
clearInterval(time);
}
}
document.getElementById("play").onclick = start;
最佳答案
var isRunning = false;
var timeoutId; // Where the timeout id will be stored.
function start() {
if(isRunning == false) {
isRunning = true;
timeoutId = setInterval(time, 1000);
document.getElementById("play").className = "fa fa-pause";
}
else if(isRunning == true) {
isRunning = false;
document.getElementById("play").className = "fa fa-play";
console.log(isRunning);
clearInterval(timeoutId); // clearInterval using timeout id saved before.
}
}
document.getElementById("play").onclick = start;
欲了解更多信息,请访问 https://developer.mozilla.org/es/docs/Web/API/WindowTimers/setTimeout
关于javascript - clearInterval() 不起作用,我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502708/