Search code examples
javascriptonclickcleartimeout

clearInterval() doesn't work and I can't figure out why


I'm trying to add play/pause button to a timer with a function that decides what to do based on the value of isRunning. When clicked second time my button instead of pausing, timer adds another setTimeout it seems and I can't figure out why.

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;

Solution

  • 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;
    

    For more information visit https://developer.mozilla.org/es/docs/Web/API/WindowTimers/setTimeout