Build a Countdown Timer using 
HTML, CSS & Javascript

Build a Countdown Timer using HTML, CSS & Javascript

Hello there, we'll be building a countdown timer using HTML, CSS & Javascript. Before we proceed knowledge of the following is necessary.

  • DOM manipulation
  • If statements (conditionals)
  • Date object
  • Function
  • SetInterval Method

So let's begin!

A countdown timer basically counts downwards to zero from a predetermined time removing one second at a time till the set time is exhausted.

Countdown timers could serve a variety of purposes in different contexts/use cases such as a countdown to launch of a product, countdown to end/beginning of sales promotion, birthdays, etc.

Here we'll be applying this to NEW YEAR!

For the countdown to work, we need to set the date and time when the timer will stop, get the current time and find the difference between the current time and our end time in a function that refreshes every 1 second to reflect the current time, and then displays the result on the DOM (web page).

Meaning the timer will count down to 31st of December 2020, 12 midnight.

I will focus on Javascript in this tutorial to get the functionality working a link to the source code can be found at the end.

HTML

HTML boiler plate

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="Countdown timer.css">
    <title>New year Countdown</title>
</head>
<body>
 <div class="timer">
            <div class="time day">
                <span id="day">30</span>
                <p>Days</p>
            </div>
            <div class="time hour">
                <span id="hour">15</span>
                <p>Hours</p>
            </div>
            <div class="time minute">
                <span id="minute">40</span>
                <p>Minutes</p>
            </div>
            <div class="time second">
                <span id="second">01</span>
                <p>Seconds</p>
            </div>
        </div>

</body>
</html>

CSS

Simple styling to keep everything neat.

html, body{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
    font-family: poppins;
    font-weight: 300;
    width: 100vw;
    color: white;
    position: relative;
    background-color: rgb(39, 39, 39);
    z-index: -89999;
}



.timer{
    width: 100%;
    height: 110px;
    background: #1a1a1a;
    font-weight: 200;
    display: flex;
    position: relative;
    top: 6rem;
}

.time{
  padding: 0.8em;
  width: 100%;
  text-align: center;
  position: relative;
  top: 1em;
}

.time p{
    font-size: 10px;
      margin: 0;
}



span{
    font-size: 250%;
    margin: 0;
    padding: 0;
    text-align: center;
    align-items: center;
}

JAVASRIPT

Fun part!

//DOM calls
let day = document.querySelector('#day')
const hour = document.querySelector('#hour')
const minute = document.querySelector('#minute')
const second = document.querySelector('#second')
SET END DATE

For the countdown to work we need to set the end time that holds the date and time when the timer will stop, we do this using the Date object new DATE( ) then add .getTime( ) here the new Date will hold the end date like this new Date("Dec 31, 2020 00:00:00") while the .getTime( ) converts everything to milliseconds.

Without .getTime( ) javascript gives you this

Thu Dec 31, 2020, 00:00:00 GMT+0100 (West Africa Standard Time)

This value can not be manipulated which is why we add .getTime this is then binded to a variable which we will call endDate. We would be using const to declare it since it won't be reassigned.

const endDate= new Date("Dec 31, 2020 00:00:00").getTime();
DECLARE SETINTERVAL FUNCTION

Next, we use a function called setInterval to update the time every second, like this...

const countDownFunction = setInterval(function () {
//code here

}, 1000)

The remaining code will be written inside this function

GET CURRENT TIME

First we get the current time using new Date().getTime()

Since it is inside thesetInterval every second it will be updated to reflect the actual time, then like the first, we bind it to a variable like this..

const currentDate= new Date().getTime();
DERIVE DISTANCE BETWEEN BOTH DATES

Next, we get the time distance between the end date and the current date like this...

const timeDistance = endDate - currentDate;
console.log(timeDistance)
//10 digit numbers

Now we've done this we move on to the main calculation!

CONVERT MILLISECONDS TO DIFFERENT TIME UNITS

Earlier I mentioned that the .getTime( ) converts to milliseconds hence the value of both variables are in milliseconds, so we have to convert it back to Days, Hours, Minutes, Seconds, and milliseconds like this...

    const days = Math.floor(timeDistance / (1000 * 60 * 60 * 24))
    const hours = Math.floor((timeDistance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    const minutes = Math.floor((timeDistance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDistance % (1000 * 60)) / 1000);
    const miliseconds = Math.floor((timeDistance % (1000 * 60)));

Let me explain

1000 milliseconds = 1 second

60 seconds = 1 minutes

60 minutes = 1 hour

24 hours = 1 day

% is an operator that spits out the remainder of the division of two numbers

console.log(10 % 3)
// 1

Math.floor() converts a number to integer

console.log(Math.floor(3.9))
// 3

So here is how it works

Days

const days = Math.floor(timeDistance/ (1000 * 60 * 60 * 24))

Here we are converting milliseconds to days, now timeDistance converts the entire time to milliseconds so to get days we have to divide timeDistance by 1000 * 60 * 60 * 24 which converts its days.

Hours

const hours = Math.floor((timeDistance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))

Here just like days but a little bit different, timeDistance is divided 1000 * 60 * 60 * 24 then the remainder is divided by 1000 * 60 * 60 which will then give you the correct hours left.

Minitues

const minutes = Math.floor((timeDistance % (1000 * 60 * 60)) / (1000 * 60));

Here drawing from hours we divide timeDistance by 1000 * 60 * 60 the remainder is then divided by 1000 * 60 this will give you the precise minutes left.

Seconds

const seconds = Math.floor((timeDistance % (1000 * 60)) / 1000);

Here we are just a few steps from the base (milliseconds), we divide timeDistance by 1000 * 60 the remainder is then divided by 1000 to get the exact seconds left.

Inject into DOM

To display our values in the DOM we do this...

    second.innerHTML = seconds
    minute.innerHTML = minutes
    hour.innerHTML = hours
    day.innerHTML = days

Target the content of span wrapping the different time units, this was taken care of at the beginning of the Javascript part, all you need to do is add .innerHTML to the variable and attach days, hours, minutes, seconds variables to it using the assignment operator.

Here is what it should look like...

Timer tutorial.PNG

But that's not all, I created a UI that was used for the styling click HERE.

You can find the code HERE on GitHub

Hope this was helpful, share in the comment section your thoughts.