gpt4 book ai didi

javascript - 计时器在每次重置时都变得越来越快

转载 作者:行者123 更新时间:2023-11-29 15:26:37 24 4
gpt4 key购买 nike

每次我重置它时,计时器都会越来越快。我在想我需要使用 clearTimeout 但不确定如何实现它。这是代码:

$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
timeout();
});
})

function timeout(){
setTimeout(function () {
if (timeInSeconds > 0) {
timeInSeconds -= 1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours*3600)/60);
seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}

最佳答案

您必须将您的 setTimeout 定义为一个变量来重置它。

See Fiddle

var thisTimer;      // Variable declaration.
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function(){
clearTimeout(thisTimer); // Clear previous timeout
timeInSeconds = sessionmin * 60;
timeout();
});
})

function timeout(){
thisTimer = setTimeout(function () { // define a timeout into a variable
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}

关于javascript - 计时器在每次重置时都变得越来越快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com