gpt4 book ai didi

javascript - 如何停止和重置倒计时器?

转载 作者:行者123 更新时间:2023-12-02 21:56:27 27 4
gpt4 key购买 nike

我需要显示一个从 10 开始的倒计时器。每当我在运行时单击任何按钮,计数器就会再次重置。下面的函数运行良好,但是每当我在计数过程中单击按钮时,计时器计数器就会快进并且显示得太快。

var timeleft = 10;
var downloadTimer = setInterval(function() {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
}, 1000);

function fn_start() {
var timeleft = 10;
var downloadTimer = setInterval(function() {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
}, 1000);
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<div id="countdown"></div>
<button type='button' id='startbtn' onclick="fn_start()">Start</button>

最佳答案

每次调用函数时都需要清除间隔。

<div id="countdown"></div>
<button type='button' id='startbtn' onclick="fn_start()">Start</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
var downloadTimer; // global var

function fn_start() {
var timeleft = 10;

clearInterval(downloadTimer);

downloadTimer = setInterval(function() {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
}, 1000);
}
// If you don't need to show the timer first, comment this line
fn_start();
</script>

关于javascript - 如何停止和重置倒计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59998974/

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