Puzzles by setInterval() and clearInterval()

Hello mighty people,

I am stuck with the code below…

What I am trying to achieve is to have timer countdown stop once pause or reset button gets clicked performed by function pauseCountDown() and reset(), respectively.

However, I don’t quite understand why setInterval() does not stop after clearInterval() gets executed?

and also the flag “isPaused” gets to be set “true” after pause button gets clicked but instantly its value got changed to “false” again along with the next iteration of nonstopped setInterval().

Any ideas or thoughts what I missed or mistakes I have?

Thank you.

function TimerPanel(props) {
  var launch;
  const startCountDown = () => {
    props.setIsPaused(false)
    var secLeft = parseInt(props.timerNow.min) * 60 + parseInt(props.timerNow.sec)
    launch = setInterval(() => {
      if (secLeft > 0 && !props.isPaused) {
        secLeft--;
        var minCountDown = Math.floor(secLeft / 60)
        var secCountDown = Math.floor((secLeft % 60) * 100) / 100
        props.setTimerNow({...props.timerNow, min: minCountDown, sec: secCountDown})
      }
    }, 1000)
  }
  const pauseCountDown = () => {
    props.setIsPaused(true)
    clearInterval(launch)
  }
  const reset = () => {
    props.setIsPaused(false)
    clearInterval(launch)
    props.setSessionLength(props.initialTimer.min);
    props.setTimerNow({...props.timerNow, min: props.initialTimer.min, sec: props.initialTimer.sec})
  }

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.