简体   繁体   中英

setInterval in a countdown timer gets executed multiple times after first round

Hope y'all staying safe

i'm trying to figure out a simple countdown timer with these codes below:

what happens is first time i click it it goes fine, counting down the number by seconds as how it should work. however from second time it becomes "faster", it goes 2 numbers per second. 3rd time it goes 3 numbers per second, or if i clicked it a few times at once it also goes "faster"

I assume its because the interval is adding up (somehow?) and execute the same code n* times per second. but i don't know where /how i should clear the interval completely each time?

hope this make sense to you guys and thanks in advance for help

    function makeTimer(){
  
  document.getElementById("button-1").innerHTML = "Stop Countdown";
  timeLeft = document.getElementById("set-time").value;
 
  // buttonChange()
  document.getElementById("set-time").value = ""
    setInterval(function(){
      if(timeLeft <=0){
        clearInterval(timeLeft = 0)
      }
          document.getElementById("timer-id").innerHTML = timeLeft+"s"
          timeLeft = timeLeft - 1

    },1000)
    
}

function toggleTimer(){
  // clearInterval(timeLeft)
  button = document.getElementById("button-1")
  if(button.innerHTML ==='Click to countdown'){
    makeTimer()
  }else if(button.innerHTML=== "Stop Countdown"){
    clearInterval(timeLeft = 0)
    button.innerHTML = "Click to countdown"
  }
}

You're using clearInterval incorrectly.

setInterval returns a reference to your timer, which you then have to pass to clearInterval to stop it.

Example:

var myTimer = setInterval(myFunction, 1000); //Starts the timer

clearInterval(myTimer); //Stops the timer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM