简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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