具有播放和暂停切换功能的JavaScript计时器

时间:2020-03-16 09:44:47

标签: javascript setinterval clearinterval

我正在尝试构建一个简单的JavaScript计时器以及一个“暂停开始”按钮切换按钮。不仅仅是播放/暂停,它似乎同时启动了多个计时器实例。有什么建议可以解决这里的问题吗?

// Define the button and timer variables globally
let playPauseToggleButton = document.querySelector('#playPauseToggleButton');
let timerDuration = 5 * 60;
let timerPaused = true;

playPauseToggleButton.addEventListener("click", pausePlay);

// Define the start of the timer, which is triggered by the button pressing "Pause" or "Play"
function startTimer(timerDuration, timerPaused) {
  function ticker() {
    timerDuration--;
    let display = document.querySelector('#timerbox');
    display.innerHTML = timerDuration;
  }
  let timer = setInterval(ticker(), 1000);
  if (timerPaused) {
    clearInterval(timerDuration);
    return timerDuration;
  } else {
    timer = setInterval(ticker(), 1000);
    return timerDuration;
  }
}

// Changing the button between "pause" and "play" and playing / pausing timer
function pausePlay() {
  if (timerPaused == false) {
    timerPaused = false; // Start the timer
    timerDuration = startTimer(timerDuration, timerPaused);
    playPauseToggleButton.innerHTML = "Pause";
  } else {
    timerPaused = true; // Pause the timer
    playPauseToggleButton.innerHTML = "Play";
    timerDuration = startTimer(timerDuration, timerPaused);
  }
}
<button id="playPauseToggleButton">Play</button>
<div id="timerbox">Display the timer countdown here</div>

0 个答案:

没有答案