我尝试将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;
答案 0 :(得分:3)
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