Countdown timers are a kind of a virtual clocks which count the time until a specific date to mark the start or end of a special occasion. They were mostly used on the landing page of new upcoming websites but now they have found their way into e-commerce websites.

The “time is running out” element on the countdown pages helps create urgency to generate more conversions on E-commerce websites. Timers can also be used on websites or blogs in order to display a countdown for special events i.e. anniversaries, birthdays, meetings etc. Countdown timers can also be used to count down the time till an offer becomes available

In this how-to guide we will make a time counter in vanilla JavaScript, instead of using third party libraries or plugins. The benefits of creating the countdown clock in vanilla JavaScript are as follows:

  • The code is lighter because there are no dependencies.
  • Improves website performance as there is no need to load any external stylesheets and scripts.

How to create a countdown timer in JavaScript

The basics of the countdown timer are as follows:

Set the End Date of the timer

The first step of creating a countdown timer is to set the end date of the timer. In this step we will declare a variable and assign it the value of the end date of our timer using the Date object:

var endDate = new Date(‘Aug 20, 2021 00:00:00’).getTime();

In the above example we have used the .getTime() method; this is because the .getTime() method converts the Date into a more usable format. It returns the number of milliseconds that have passed since the midnight of Jan 1, 1970 which makes it easier to perform mathematical operations on the endDate variable.

Make a Timing Event funcion

Now we will make a setInterval() function which will repeatedly execute the code inside it after the specified time interval. This is because we want to update our timer after every second:

var countDownTimer = setInterval(() => {

// All of the JavaScript code mentioned below goes inside this function

}, 1000);

The setInterval() function takes the interval argument in milliseconds; as there are 1000 milliseconds inside a second and we want to refresh the counter after every second, we have given 1000 as the interval of the timing event function.

Calculating The Time

Now we will write code inside the setInterval() function. In this step we will calculate the time remaining till the end time of the counter:

var now = new Date().getTime();

var remainingTime = endDate now;

Now the value of the remaining time present in the variable remainingTime is in the form of milliseconds but we want to show the remaining number of Days, Hours, Minutes and Seconds so we will need to convert the number of milliseconds into our required time periods:

const second = 1000;

const minute = second * 60;

const hour = minute * 60;

const day = hour * 24;

daysLeft = Math.trunc(remainingTime / day);

hoursLeft = Math.trunc((remainingTime % day) / hour);

minutesLeft = Math.trunc((remainingTime % hour) / minute);

secondsLeft = Math.trunc((remainingTime % minute) / second);

There are 1,000 milliseconds inside a second, 60,000 milliseconds (1000*60) inside a minute, 3,600,000 milliseconds (1000*60*60) in an hour and 86,400,000 milliseconds (1000*60*60*24) in a day.

We have calculated the days left by dividing the amount of milliseconds present in remainingTime by the amount of milliseconds in one day; If there are 86,400,000 milliseconds left then daysLeft will be equal to one (86,400,000/86,400,000), if there are 172,800,000 milliseconds left then daysLeft will be equal to 2 (172,800,000/86,400,000) and so on. The number returned by the (remainingTime / day) operation will most often be a decimal number but we only need the whole number part so we have used the Math.trun() method.

To calculate the hoursLeft we first got rid of the days by using the modulus operator. Then we calculated the hours from the remaining time. We can calculate the minutesLeft and secondsLeft variables similarly.

Displaying The Timer

In this step we will add some code (tags) into the HTML body; then we will access those tags in the setInterval() function and modify them to show the timer on the webpage:

<p id=“days”></p>

<p id=“hours”></p>

<p id=“minutes”></p>

<p id=“seconds”></p>

Inside the setInterval() function:

document.querySelector(‘#days’).innerHTML = daysLeft ‘ Days’;

document.querySelector(‘#hours’).innerHTML = hoursLeft ‘ Hours’;

document.querySelector(‘#minutes’).innerHTML = minutesLeft ‘ Minutes’;

document.querySelector(‘#seconds’).innerHTML = secondsLeft ‘ Seconds’;

Now we will add some more code in the setInterval() function which will be executed in case the timer is up:

if (remainingTime <= 0) {

document.write(‘Time Up!’);

}

All in all the HTML file for a countdown timer should look something like this:

<!DOCTYPE HTML>

<html>

<head>

</head>

<body>

<p id=“days”></p>

<p id=“hours”></p>

<p id=“minutes”></p>

<p id=“seconds”></p>

<script>

var endDate = new Date(‘Aug 20, 2021 00:00:00’).getTime();

var countDownTimer = setInterval(() => {

var now = new Date().getTime();

var remainingTime = endDate now;

const second = 1000;

const minute = second * 60;

const hour = minute * 60;

const day = hour * 24;

daysLeft = Math.trunc(remainingTime / day);

hoursLeft = Math.trunc((remainingTime % day) / hour);

minutesLeft = Math.trunc((remainingTime % hour) / minute);

secondsLeft = Math.trunc((remainingTime % minute) / second);

document.querySelector(‘#days’).innerHTML = daysLeft ‘ Days’;

document.querySelector(‘#hours’).innerHTML = hoursLeft ‘ Hours’;

document.querySelector(‘#minutes’).innerHTML = minutesLeft ‘ Minutes’;

document.querySelector(‘#seconds’).innerHTML = secondsLeft ‘ Seconds’;

if (remainingTime <= 0) {

document.write(‘Time Up!’);

}

}, 1000);

</script>

</body>

</html>

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/09/echo/word-image-226.png" data-lazy- height="788" src="data:image/svg xml,” width=”603″>

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/09/echo/word-image-227.png" data-lazy- height="245" src="data:image/svg xml,” width=”485″>

A countdown timer has been successfully made; now you can style it using CSS.

Conclusion

Countdown timers are used by soon to be live websites as well as many ecommerce websites. The ecommerce websites use timers to persuade the customer to make quick decisions. The resolution of this post was to explore the making of a countdown timer in JavaScript.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/09/echo/7011409B3A384F43A8417D1DAC68D179-150×150.jpg613d08c85f255.jpg" height="112" src="data:image/svg xml,” width=”112″>

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.