简体   繁体   English

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

[英]How to stop and reset a countdown timer?

I need to display a countdown timer starting with 10. Whenever I click any button while it is running, the counter will reset again.我需要显示一个从 10 开始的倒数计时器。每当我在运行时单击任何按钮,计数器都会再次重置。 The below function is working well but whenever I am clicking the button in the midst of the counting, the timer counter is fast forwarding and showing too fast.下面的功能运行良好,但是每当我在计数过程中单击按钮时,计时器计数器都会快进并且显示得太快。

 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>

You need to clear the interval every time you call your function.每次调用函数时都需要清除间隔。

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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