reset countdown timer javascript

Reset Countdown Timer JavaScript

If you are working on a countdown timer in JavaScript and want to reset it to its initial value, you can do so with a few lines of code.

Method 1: Using clearTimeout()

The first method involves using the clearTimeout() method. This method clears the timeout set by the setTimeout() method, which is commonly used to create a countdown timer.


// Set the initial value of the countdown timer
var countdown = 60;

// Create a reference to the setTimeout() method
var timer = setTimeout(function() {
  // Countdown timer logic here
}, 1000);

// Reset the countdown timer
clearTimeout(timer);
countdown = 60;

In this example, we create a reference to the setTimeout() method and store it in a variable called "timer". When we want to reset the countdown timer, we simply call the clearTimeout() method with the "timer" variable as its argument. We then set the countdown variable back to its initial value.

Method 2: Using setInterval()

The second method involves using the setInterval() method. This method repeatedly calls a function at a specified interval, which can be used to update a countdown timer.


// Set the initial value of the countdown timer
var countdown = 60;

// Create a reference to the setInterval() method
var interval = setInterval(function() {
  countdown--;
  
  // Update the countdown timer display
  document.getElementById("countdown-timer").innerHTML = countdown;
  
  if (countdown == 0) {
    // Countdown timer logic here
    
    // Reset the countdown timer
    clearInterval(interval);
    countdown = 60;
  }
}, 1000);

In this example, we use the setInterval() method to decrement the countdown variable every second and update the countdown timer display. When the countdown variable reaches 0, we execute our countdown timer logic and reset the countdown timer by calling the clearInterval() method with the "interval" variable as its argument. We then set the countdown variable back to its initial value.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe