Abhishek Chattejee
Abhishek Chattejee

Reputation: 3

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>

Upvotes: 0

Views: 1381

Answers (1)

besciualex
besciualex

Reputation: 1892

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>

Upvotes: 1

Related Questions