[英]setInterval in a countdown timer gets executed multiple times after first round
希望你們都保持安全
我正在嘗試使用以下代碼找出一個簡單的倒數計時器:
發生的事情是我第一次點擊它就很好,按秒數倒數它應該如何工作。 但是從第二次開始,它變得“更快”,每秒運行 2 個數字。 第三次它每秒運行 3 個數字,或者如果我一次單擊它幾次它也會“更快”
我假設它是因為間隔加起來(不知何故?)並每秒執行相同的代碼 n* 次。 但我不知道每次應該在哪里/如何完全清除間隔?
希望這對你們有意義,並提前感謝您的幫助
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"
}
}
您使用clearInterval
不正確。
setInterval
返回對計時器的引用,然后您必須將其傳遞給clearInterval
以停止它。
例子:
var myTimer = setInterval(myFunction, 1000); //Starts the timer
clearInterval(myTimer); //Stops the timer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.