JavaScript countdown timer start stop reset

        const day = document.getElementById(‘day’);

        const hours = document.getElementById(‘hours’);

        const minutes = document.getElementById(‘minutes’);

        const seconds = document.getElementById(‘Seconds’);

        const currentYear = new Date().getFullYear();

        const newYearsTime = new Date(`January 1 ${currentYear + 1} 00:00:00`);

        function updateCountdownTime() {

            const currentTime = new Date();

            const timeDifferent = newYearsTime – currentTime;

            const d = Math.floor(timeDifferent / 1000 / 60 / 60 / 24);

            const h = Math.floor(timeDifferent / 1000 / 60 / 60) % 24;

            const m = Math.floor(timeDifferent / 1000 / 60) % 60;

            const s = Math.floor(timeDifferent / 1000) % 60;

            hours.innerHTML = h < 10 ? ‘0’ + h : h;

            minutes.innerHTML = m < 10 ? ‘0’ + m : m;

            seconds.innerHTML = s < 10 ? ‘0’ + s : s;

 setInterval(updateCountdownTime, 1000)

In this article, we will learn how to create 30 minutes countdown timer where you can start a countdown, stop the countdown and also reset the countdown to the default value. In addition, we will add an alarm sound when the countdown reaches 0 after successfully completing 30 minutes.

JavaScript countdown timer start stop reset
30-min countdown timer with start, stop and reset

1. Create a <span></span> container for every Digit

The first step is to create HTML <span></span> element for every digit that needs to be display in the countdown clock. For 30 minutes countdown, we need 4 digits with 2 each to display minutes and seconds remaining in the countdown. Additionally, we also add a “:” separator to divide minutes and seconds timing.

<div>
   <span class="count-digit">3</span>
   <span class="count-digit">0</span>
   <span class="separator">:</span>
   <span class="count-digit">0</span>
   <span class="count-digit">0</span>
</div>

2. Add buttons for start, stop and reset actions

Once we are displaying the minutes and seconds of the count, now we will add HTML buttons for the start, stop and reset actions of the timer. For CSS code for timer and buttons please refer “Final solution code” section at the end of this article.

<div class="options">
   <button id="stop-timer">
     <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
   </button>
   <button id="start-timer">
     <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
   </button>
   <button id="reset-timer">
     <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
   </button>
</div>
30 min countdown timer preview30-min Countdown timer with HTML and CSS code

3. Function to Generate countdown string

Before we add any JavaScript functionality to the app, we need to create JavaScript functions to support countdown timer functionalities. Creating separate functions allows for the reuse of the code and makes it easier to modify/add existing functionalities.

First, we will create a function to generate the countdown string which requires remaining time in seconds. Displaying the countdown directly in seconds is less readable, hence will generate the countdown string in “MM:SS” format and append zeros for single-digit values.

// Default inital value of timer
const defaultValue = 30 * 60;

// variable to the time
var countDownTime = defaultValue;

// Function calculate time string
const findTimeString = () => {
  var minutes = String(Math.trunc(countDownTime / 60));
  var seconds = String(countDownTime % 60);
  if (minutes.length === 1) {
    minutes = "0" + minutes;
  }
  if (seconds.length === 1) {
    seconds = "0" + seconds;
  }
  return minutes + seconds;
};

4. Function to Update and Display countdown

Once we are able to generate the string in

“MM:SS” format, now we have to display the string on the screen. We select every <span></span> containers created in step 1 using “querySelectorAll” method and iterate over the list and assigning the DOM innerHTML with the characters of the countdown string.
// Select Every Count Container
const countContainer = document.querySelectorAll(".count-digit");

// Function to display coundown on screen
const renderTime = () => {
  const time = findTimeString();
  countContainer.forEach((count, index) => {
    count.innerHTML = time.charAt(index);
  });
};

5. Start timer functionality

At the start of the timer countdown, we initialize runCountDown function to run after every second. In the runCountDown method, we decrement the countdown time and display it on the screen. Additionally, on timeout, the countdown is stopped by using clearInterval(), and the countDownTime is set to the default value.

const startAction = document.getElementById("start-timer");

// Function to start Countdown
const startTimer = () => {
  if (isStopped) {
    isStopped = false;
    timerID = setInterval(runCountDown, 500);
  }
};

startAction.onclick = startTimer;

// function to execute timer
const runCountDown = () => {
  // decrement time
  countDownTime -= 1;
  //Display updated time
  renderTime();

  // timeout on zero
  if (countDownTime === 0) {
    stopTimer();
    countDownTime = defaultValue;
  }
};

6. Stop timer functionality

For stopping the timer, we just need to perform clearInterval() with the timeID retrieved earlier from setInterval() in start timer functionality.

const stopAction = document.getElementById("stop-timer");

// Function to stop Countdown
const stopTimer = () => {
  isStopped = true;
  if (timerID) {
    clearInterval(timerID);
  }
};

stopAction.onclick = stopTimer;

7. Reset timer functionality

To reset the timer, in addition to stopping the timer, we need to reset the countDownTime value and display the updated value on the screen.

How to reset countdown timer in JavaScript?

Resetting the timer funcitons in JavaScript setTimeout function sets the timer and executes it after the set time, before that if we want to cancel or reset the timer then we must use the clearTimeout function with timer id.

How to make simple JavaScript timer with start stop and reset button?

function _timer(callback).
var time = 0; // The default time of the timer..
var mode = 1; // Mode: count up or count down..
var status = 0; // Status: timer is running or stoped..
var timer_id; // This is used by setInterval function..
// this will start the timer ex. start the timer with 1 second interval timer.start(1000).

How to stop countdown timer in JavaScript?

The clearTimeout() method clears a timer set with the setTimeout() method.

How to pause and resume countdown timer in JavaScript?

// 10 minutes from now..
var time_in_minutes = 10;.
var current_time = Date. parse(new Date());.
var deadline = new Date(current_time + time_in_minutes*60*1000);.
function time_remaining(endtime){.
var t = Date. parse(endtime) - Date. parse(new Date());.