mercredi 12 février 2020

How to use setInterval() and clearInterval() in the same function

I'm trying to create a function that starts and stops a timer. The starting is always on the click of a button, but the stopping can be due to the timer running down or the function being called again from another function.

This is what I have so far. Works perfect for what you see but I cannot figure out how to incorporate clearInterval() so that it stops when the game is won. The functioning calling timerCountdown is located in a different js file. I've read answers to similar questions but they are all seem to be doing it a little differently to where I can't make it work for my case

I do realize that I need to call clearInterval(count) but I don't know how to incorporate this into the function itself.

const timerCountdown = () => {                             
  let count = setInterval(() => {
    let timeLeft = timer.innerHTML
    if (timeLeft > 0) {
      timer.innerHTML = timeLeft - 1
    } else {
      gameOverMessage()
    }
  }, 1000) 
}

Aucun commentaire:

Enregistrer un commentaire