# How to Build a JavaScript Countdown Timer

In this tutorial, we’ll be implementing a timer to countdown to a specific date or time using vanilla JavaScript. We’ll also implement a feature to display content on a webpage once the countdown is done.

## Watch the Video

Tuts+ Instructor Adi Purdila has created a video version of this tutorial, if you prefer video format. Don’t forget to subscribe to youtube.com/@envatotuts for more free courses and tutorials!

## JavaScript Timer Demo

A countdown timer on a webpage is usually used to indicate the end or beginning of an event. It can be used to let customers know when a price offer expires, or feature on a “coming soon” landing page to indicate when the site will be published. It can also be used to let a user know if an action needs to be carried out soon; for example, some websites will log users out of a page if there has been no activity within a certain period of time.

So, back to what we’re making—here’s a look at the final product. Press Rerun on the demo to start the countdown function:

Let’s get started!

## 1. Creating the Markup

We’ll be using two sections for this demo: a timer section and a content section. The timer section will contain the elements for displaying the time left in the countdown and the content section will be the element shown after the countdown is up.

 1 
 2 

This content will be displayed in

 3 
 4  0 days  5  0 hours  6  0 minutes  7  and  8  0 seconds  9 
 10 
 11 12 
 13 

Hello, World

 14 


### Considering Accessibility

Since we’re building a section that has constantly changing information, we should consider how this information will be presented to assistive technologies. In this demo, we’ll use the timer role to represent the elements that have regularly updated text.

 1 
 2 

This content will be displayed in

 3 
 4  0 days  5  0 hours  6  0 minutes  7  and  8  0 seconds  9 
 10 
 11 12 
 13 

Hello, World

 14 


## 2. Styling the Sections

The timer container has the most priority when the page is first loaded so we’ll make it a fixed container that’s the full width and height of the page so no other content is visible till the countdown is up. We’ll also use an opacity styling on our content to hide it.

 1 #timer {  2  position: fixed;  3  top: 0;  4  bottom: 0;  5  display: flex;  6  flex-direction: column;  7  min-height: 100vh;  8  justify-content: center;  9  align-items: center;  10  width: 100%;  11  z-index: 2;  12 }  13 14 #content {  15  opacity: 0;  16 } 

## 3. Building the Countdown Timer

This is the logic we’ll use to handle the countdown timer:

1. Define a countdown value based on a specific date or time
2. Get the current date and subtract the value from our countdown
3. Carry out the subtraction function at an interval of 1s
4. If the countdown date is less than or equal to the current date, end the countdown

Let’s start with defining our countdown value. There are two possible methods we can use:

### 1. Defining the Countdown Value as a Specific Date and Time

We can initialise a countdown value as a specific date using the Date() constructor. This method is useful for displaying special offers or discounts as the countdown end time will always be constant. For example, you can use a countdown timer to display a discount offer until the New Year.

 1 let countdownDate = new Date('01 January 2023 00:00') 

### 2. Defining the Countdown Value as an Added Unit of Time to the Current Date

We can also initialise a countdown timer by adding time to the current date. This method is useful for handling user-based timer interactions. We use the Date get and set methods for this. For example, you can set a timer to display content 30 seconds after a user has landed on a webpage.

 1 let countdownDate = new Date().setSeconds(new Date().getSeconds() + 30); 

We can also modify this function for minutes or hours:

 1 let countdownDate = new Date().setMinutes(new Date().getMinutes() + 5); 
 1 let countdownDate = new Date().setHours(new Date().getHours() + 1) 

Once we’ve setup our countdown value, we can define our constants:

 1 const daysElem = document.getElementById("days"),  2  hoursElem = document.getElementById("hours"),  3  minutesElem = document.getElementById("minutes"),  4  secondsElem = document.getElementById("seconds"),  5  timer = document.getElementById("timer"),  6  content = document.getElementById("content"); 

Then we can work on our countdown function.

## 4. Creating the startCountdown() Function

We’ll create a new function called startCountdown() where we get the current date and subtract it from the countdown date. We’ll use the Date.getTime() method to convert both values into milliseconds then we divide the difference by 1,000 to convert to seconds.

 1 const startCountdown = () => {  2  const now = new Date().getTime();  3  const countdown = new Date(countdownDate).getTime();  4 5  const difference = (countdown - now) / 1000;  6 } 

We’ll need to convert the difference value to days, hours, minutes and seconds to determine our timer value.

We can convert seconds to days by dividing the difference in seconds by the value of one day (60seconds * 60minutes * 24hours) and rounding up to the nearest value.

 1 let days = Math.floor(difference / (60 * 60 * 24)); 

Since our countdown is an additive value, we’ll need to take into consideration the preceding values when calculating. When converting to hours, we’ll first need to know how many days are in the difference and then convert the remainder to hours.

For example, if we have 90,000 seconds, this will be converted to 25 hours. However, we can’t display a countdown as 1 day and 25 hours as that will be an incorrect time. Instead we’ll first calculate how many days are in the seconds as 90000 / (60 * 60 * 24) = 1 day with a remainder of 3600 seconds. Then we can convert this remainder to hours by dividing by (60seconds * 60minutes) which gives 1 hour.

 1 let hours = Math.floor((difference % (60 * 60 * 24)) / (60 * 60)); 

Applying the same cumulative division for minutes and seconds:

 1  let minutes = Math.floor((difference % (60 * 60)) / 60);  2  let seconds = Math.floor(difference % 60); 

Then we’ll pass our calculated values into the HTML elements. Taking grammar into consideration, we can define a function to format the unit of time text as singular or plural based on the value of time.

 1 const formatTime = (time, string) => {  2  return time == 1 ? ${time}${string} : ${time}${string}s;  3 }; 

Our startCountdown() function now looks like this:

 1 const startCountdown = () => {  2  const now = new Date().getTime();  3  const countdown = new Date(countdownDate).getTime();  4 5  const difference = (countdown - now) / 1000;  6 7  let days = Math.floor(difference / (60 * 60 * 24));  8  let hours = Math.floor((difference % (60 * 60 * 24)) / (60 * 60));  9  let minutes = Math.floor((difference % (60 * 60)) / 60);  10  let seconds = Math.floor(difference % 60);  11 12  daysElem.innerHTML = formatTime(days, "day");  13  hoursElem.innerHTML = formatTime(hours, "hour");  14  minutesElem.innerHTML = formatTime(minutes, "minute");  15  secondsElem.innerHTML = formatTime(seconds, "second");  16 }; 

## 5. Running our Function at Intervals

Now we have our countdown function, we’ll create a function that runs the countdown function at an interval of 1s.

First, we’ll create our timerInterval value.

 1 let timerInterval 

Then we define the timerInterval as a setInterval function when the page loads

 1 window.addEventListener("load", () => {  2  startCountdown();  3  timerInterval = setInterval(startCountdown, 1000);  4 }); 

In this method, we’ve called the startCountdown() function immediately as the page loads to update the countdown values and then we call the countdown function every 1s after the page loads.

We’ll need to also define a function to handle when the countdown timer ends. We’ll know the timer has ended when the difference in our startCountdown function is less than 1 second.

 1 const startCountdown = () => {  2  const now = new Date().getTime();  3  const countdown = new Date(countdownDate).getTime();  4 5  const difference = (countdown - now) / 1000;  6 7  if (difference < 1) {  8  endCountdown();  9  }  10   11  ...  12 }; 

This is what we have so far!

## 6. When the Countdown Timer Ends

What we currently have keeps counting down indefinitely, which clearly isn’t very useful, so let’s remedy that.

In our endCountdown() function, we’ll stop the interval function, delete the timer and display the content section.

 1 const endCountdown = () => {  2  clearInterval(timerInterval);  3  timer.remove();  4  content.classList.add("visible");  5 }; 

We’ll target the visible class in CSS to handle displaying the content. In this demo, we have a text scale and background colour change animation when the content is displayed that’s also handled with CSS. Of course, this is purely for demonstrative purposes—you can style things however you want.

 1 #content h1 {  2  font-size: 10vmax;  3  transform: scale(1.25);  4 }  5 6 #content.visible {  7  opacity: 1;  8  animation: colorChange 1s ease-in-out 0.5s forwards;  9 }  10 11 #content.visible h1 {  12  animation: scaleOut 1s ease-in-out 0.5s forwards;  13 }  14 15 @keyframes colorChange {  16  from {  17  color: #fcdf00;  18  background-color: #0d67ad;  19  }  20  to {  21  color: white;  22  background-color: black;  23  }  24 }  25 26 @keyframes scaleOut {  27  from {  28  transform: scale(1.25);  29  }  30  to {  31  transform: scale(1);  32  }  33 } 

## Conclusion

And, with that, we’ve successfully created a countdown timer to display content on a webpage!