[英]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.但是从第二次开始,它变得“更快”,每秒运行 2 个数字。 3rd time it goes 3 numbers per second, or if i clicked it a few times at once it also goes "faster"第三次它每秒运行 3 个数字,或者如果我一次单击它几次它也会“更快”
I assume its because the interval is adding up (somehow?) and execute the same code n* times per second.我假设它是因为间隔加起来(不知何故?)并每秒执行相同的代码 n* 次。 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.您使用clearInterval
不正确。
setInterval
returns a reference to your timer, which you then have to pass to clearInterval
to stop it. setInterval
返回对计时器的引用,然后您必须将其传递给clearInterval
以停止它。
Example:例子:
var myTimer = setInterval(myFunction, 1000); //Starts the timer
clearInterval(myTimer); //Stops the timer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.