# Create a JavaScript countdown timer

*Last updated: September 27, 2022.*

In this tutorial, we are going to show you how you can build a countdown timer using HTML, CSS and JavaScript.

The countdown timer will refresh itself every second (no need for the user to refresh the page).

Once complete, all that needs to be input to start a new countdown is a time and date. JavaScript then takes care of the necessary calculations and updates the DOM to create the new countdown.

Once complete, it will look something like this:

##### Table of contents

## Step 1: HTML markup

The HTML should include a display for the countdown and labels for each unit.

Below, we use a `<table>`

element in which the countdown and labels are contained in separate rows.

```
<table id="countdown">
<tr id="countdown-timer">
<td><span id="days">x</span></td>
<td><span id="hours">x</span></td>
<td><span id="minutes">x</span></td>
<td><span id="seconds">x</span></td>
</tr>
<tr id="countdown-labels">
<td><span>Days</span></td>
<td><span>Hours</span></td>
<td><span>Minutes</span></td>
<td><span>Seconds</span></td>
</tr>
</table>
```

Note: the `x`

values in the countdown display are just placeholders that will be replaced immediately by the countdown values. The user will not see these placeholder values.

## Step 2: Programming a countdown with JavaScript

### Calculating time remaining in milliseconds

We start by creating a new `Date()`

object, with its value set to the desired countdown date and time.

Next, we create a function that will update the countdown each time it is called.

Inside, initialize a new `Date()`

object, which returns the time *now*.

Then, subtract the value of `now`

from `countingDownTime`

. This gives the amount of time between now and the countdown time in milliseconds.

```
const storeOpening = new Date('jan 01, 2023 00:00:00');
setCountdown(storeOpening); // Calls setCoundown once
function setCountdown(countingDownTime) {
let now = new Date();
let timeRemaining = countingDownTime - now;
console.log(timeRemaining); // timeRemaining is time left in milliseconds!
}
```

This works because, under the hood, a `Date()`

object value is the number of milliseconds that have passed since Jan 1, 1970 (UNIX epoch time).

### Converting time remaining to regular units

Next, you’ll want to calculate the time remaining until the countdown in each unit.

You do this by dividing `timeRemaining`

(in milliseconds) by the next greater number of units.

For example, to get the minutes remaining, you can divide the milliseconds remaining by 1000 to give seconds remaining. Then, divide the seconds remaining by 60 to give the hours remaining.

Or, for short, divide the milliseconds remaining by the second and minutes remaining multiplied:

```
const storeOpening = new Date('jan 01, 2023 00:00:00');
setCountdown(storeOpening); // Calls setCoundown once
function setCountdown(countingDownTime) {
let now = new Date();
let timeRemaining = countingDownTime - now;
console.log(timeRemaining); // timeRemaining is time left in milliseconds!
// Now to convert this into time remaining in regular units
// Seconds
let seconds = Math.floor(timeRemaining / 1000);
// Minutes
let minutes = Math.floor(timeRemaining / (1000*60));
// Hours
let hours = Math.floor(timeRemaining / (1000*60*60));
// Days
let days = Math.floor(timeRemaining / (1000*60*60*24));
console.log(days, hours, minutes, seconds); // Absolute time left in each unit!
}
```

### Getting the correct display value for each unit

This gives the time remaining in each unit. But a countdown displays the time remaining across all units.

To calculate this, you need to subtract the bigger units of time from smaller ones.

For example, hours to display should not be the number of hours to go until the countdown. It should be the hours to go minus the number of hours left that are represented by the days.

And minutes should exclude all the minutes already represented by hours. And seconds all the seconds represented by minutes already.

```
const storeOpening = new Date('jan 01, 2023 00:00:00');
setCountdown(storeOpening); // Calls setCoundown once
function setCountdown(countingDownTime) {
let now = new Date();
let timeRemaining = countingDownTime - now;
console.log(timeRemaining); // timeRemaining is time left in milliseconds!
// Now to convert this into time remaining in regular units
// Seconds
let seconds = Math.floor(timeRemaining / 1000);
// Minutes
let minutes = Math.floor(timeRemaining / (1000*60));
// Hours
let hours = Math.floor(timeRemaining / (1000*60*60));
// Days
let days = Math.floor(timeRemaining / (1000*60*60*24));
console.log(days, hours, minutes, seconds); // Absolute time left in each unit!
// Now subtract the bigger units of time from the smaller ones
let daysToDisplay = days;
// Subtract 24 hours for every day remaining from the hour count
let hoursToDisplay = hours - (days * 24);
// Subtract 60 minutes for every hour remaining from the minute count
let minutesToDisplay = minutes - ( hours * 60 );
// Subtract 60 seconds for every minute remaining from the seconds count
let secondsToDisplay = seconds - ( minutes * 60 );
console.log(daysToDisplay, hoursToDisplay, minutesToDisplay, secondsToDisplay);
// Countdown now in displayable format!
}
```

Now we have the correct display value for each unit.

### Printing to the DOM

To complete the function, select the countdown display elements in the HTML markup and set each value to the respective unit calculation.

```
const storeOpening = new Date('jan 01, 2023 00:00:00');
setCountdown(storeOpening); // Calls setCoundown once
function setCountdown(countingDownTime) {
let now = new Date();
let timeRemaining = countingDownTime - now;
console.log(timeRemaining); // timeRemaining is time left in milliseconds!
// Now to convert this into time remaining in regular units
// Seconds
let seconds = Math.floor(timeRemaining / 1000);
// Minutes
let minutes = Math.floor(timeRemaining / (1000*60));
// Hours
let hours = Math.floor(timeRemaining / (1000*60*60));
// Days
let days = Math.floor(timeRemaining / (1000*60*60*24));
console.log(days, hours, minutes, seconds); // Absolute time left in each unit!
// Now subtract the bigger units of time from the smaller ones
let daysToDisplay = days;
// Subtract 24 hours for every day remaining from the hour count
let hoursToDisplay = hours - (days * 24);
// Subtract 60 minutes for every hour remaining from the minute count
let minutesToDisplay = minutes - ( hours * 60 );
// Subtract 60 seconds for every minute remaining from the seconds count
let secondsToDisplay = seconds - ( minutes * 60 );
console.log(daysToDisplay, hoursToDisplay, minutesToDisplay, secondsToDisplay);
// Countdown now in displayable format!
// Print to DOM
const daysEl = document.getElementById('days');
const hoursEl = document.getElementById('hours');
const minutesEl = document.getElementById('minutes');
const secondsEl = document.getElementById('seconds');
daysEl.textContent = daysToDisplay;
hoursEl.textContent = hoursToDisplay;
minutesEl.textContent = minutesToDisplay;
secondsEl.textContent = secondsToDisplay;
}
```

## Step 3: Calling the countdown function

To start the countdown, call the `setCountdown`

function once initially.

Then, using `setInterval()`

, call it every second. This will keep the countdown updating without the need for a page refresh.

```
// Sets the coundown upon page load:
setCountdown(storeOpening);
// Sets the countdown after every second:
setInterval(function() {
setCountdown(storeOpening);
},1000);
```

Now that the countdown is ticking, the final step is to add some CSS.

## Step 4: CSS

Finally, let’s add some minimal CSS to give the countdown some basic formatting you can build upon:

```
body { /* centers countdown */
display: flex;
justify-content: center;
}
#countdown {
font-size: 2rem;
text-align: center;
margin: 1rem;
}
#countdown-timer span {
display: inline-block; /* Necessary to set a width */
padding: 1rem;
width: 200px;
margin: 0.5rem;
border: 1px grey solid;
}
```

Your countdown should now look something like this:

To get the same styling as the project preview, you can use the CSS in the live project preview.

## Summary

In this tutorial we have seen how a countdown timer can be created using HTML, CSS and vanilla JavaScript.

Check out our projects section to further sharpen your HTML, CSS and JavaScript skills!

### Related links

- OpenJavaScript
- MDN Web Docs: Date() Constructor