Skip to content Skip to sidebar Skip to footer

SetInterval And ClearInterval Through Button Click Events

Here is my code: window.onload = runThis; function runThis() { const txtMin = document.getElementsByClassName('min'); const txtSec = document.getElementsByClassName('sec');

Solution 1:

Try to set the ID of the interval in the "go" function in a variable outside to be canceled inside the "stopIt" function, like this:

window.onload = runThis;
function runThis() {
  var intervalID = null;
  const txtMin = document.getElementsByClassName("min");
  const txtSec = document.getElementsByClassName("sec");

  function go() {
    intervalID = setInterval(countDown, 1000);
  }

  function countDown() {
    timeNow = timeNow - 1;
    timeSec = timeNow % 60; //remainder as seconds
    timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes

    txtMin[0].innerText =
      (timeMin > 0 ? 
        (timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
      : "00:");

    txtSec[0].innerText =
      (timeSec > 0 ? 
        (timeSec >= 10 ? timeSec : `0${timeSec}`)
      : "00");
  }

  function stopIt() {
    clearInterval(intervalID);
  }

  const btnStart = document.getElementsByClassName("start");
  btnStart[0].addEventListener("click", go);

  const btnStop = document.getElementsByClassName("stop");
  btnStop[0].addEventListener("click", stopIt);
}

Post a Comment for "SetInterval And ClearInterval Through Button Click Events"