1

我正在尝试将按钮添加到具有根据isRunningplay/pause的值决定做什么的功能的计时器。当第二次单击我的按钮而不是暂停时,计时器似乎又增加了一个,我不知道为什么。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;
4

1 回答 1

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

于 2016-07-21T12:46:01.480 回答