Search code examples
javascripttimercountdownclearinterval

how to stop my timer after it reaches below zero


How come either of these options dont work to stop my timer once it reaches below zero?

var timeLeft = 20

let timer = () => {
  setInterval(() => {
    timeLeft--
    timeLimitEl.textContent = timeLeft
    console.log(timeLeft)
    if (timeLeft < 0) {
      // option 1 - did not work
      // clearInterval(timer)
      // option 2 - did not work
      // return
    }
  }, 1000)
}

Solution

  • setInterval returns an id of the interval. You have to call clearInterval with that id

    var timeLeft = 5
    let handle
    
    let timer = () => {
      handle = setInterval(() => {
        timeLeft--
        //timeLimitEl.textContent = timeLeft
        console.log(timeLeft)
        if (timeLeft < 0) {
          clearInterval(handle)
        }
      }, 1000)
    }
    
    timer()