Javascript Countdown Timer


In this article, we will create a javascript countdown timer app that takes the user's birthday as input and create a timer for the user's next birthday. Source code is given.

What is a countdown timer?

A countdown timer is a clock running on any landing page with decreasing time on it. It points to a certain event that is either to come or going to end.

Suppose you have an eCommerce website and a product to sell and you offer a discount for a limited period of time, then your countdown time will indicate the time in which offer is going to expire.

The countdown timer can also indicate how much time left to some event.

In this tutorial, you will learn how to make a countdown timer with javascript. It will be a birthday countdown which will indicate how much time left to your next birthday.

Here is the final birthday countdown timer you are going to make.

javascript countdown timer
Test the app

Creating Project Structure

First, create a folder with name birthday-countdown. In this folder create 3 files:

Second, download birthday celebration image to this project folder which will be used for the background of the birthday countdown.

You create project folder will look like this:

project structure birthday countdown

Creating HTML for countdown

The HTML code for the countdown timer is quite simple. In head section it connects to the style.css using <link> tag and in body section it connects to script.js file using <script> tag.

The HTML code contains a <div> element with class name 'countdown', it holds everything about the timer app.

Let's first see the complete HTML code for the countdown timer app.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Countdown Timer</title>
  <link rel="stylesheet" href="./style.css">
</head>

<body>
  <div class="countdown-timer">
    <h1 class="greet">Timer To Your Next Birthday 🎂</h1>
    <ul>
      <li>
        <span class="days"></span>
        <span>DAYS</span>
      </li>
      <li>
        <span class="hours"></span>
        <span>HOURS</span>
      </li>
      <li>
        <span class="minutes"></span>
        <span>MINUTES</span>
      </li>
      <li>
        <span class="seconds"></span>
        <span>SECONDS</span>
      </li>
    </ul>
    <p class="coming-year"></p>
  </div>
  <script src="./script.js"></script>
</body>

</html>

The body tag in the above code contains an element with class 'countdown-timer' which holds all elements of the app.


Date object in javascript

Before we go through javascript code let us first understand a few javascript logic that will be used further in the section.

To create time you will need to work with Date object. It represents a single moment in the time.

The Date object is specified as the number of milliseconds that have passed since midnight on January 1, 1970, UTC.

The following code show how to create a new Date object that represents the current date and time:

const now = new Date();

Now let's see how to get milliseconds elapsed since a date and time.

We need this because we will use this to find difference between 2 different moments of time to get time remaining to some event (birthday).

const now = new Date();
const milliseconds = now.getTime();
console.log(milliseconds); // 1611643085711

Now we know how to get time elapsed since default date (january 1, 1970) but you can also pass a date and time in form of string to get time spend since some exact date and time.

const date = new Date('jan 01, 2000 02:50:25');
const milliseconds = date.getTime();
console.log(milliseconds); // 946675225000

Calculate difference between 2 moment of time

Using above method we can find time elapsed for 2 different time and can take difference moment of time.

const date1 = new Date('oct 01, 2010 15:23:00');
const date2 = new Date('jan 01, 2000 02:50:25');

const difference = date1.getTime() - date2.getTime();
console.log(difference); // 339251555000

Calculate the remaining time

While creating countdown time you will have to calculate remaining days, hours, minutes and seconds to display it on screen.

All this information will be deduced from a number of remaining milliseconds to the event.

The following example takes 450524354 milliseconds and calculates days, hours, minutes and seconds.

Convert milliseconds to integer seconds:

To convert milliseconds to seconds divide it by 1000. Now, this is second but has fractional value.

Use Math.floor to convert it to an integer.

Then use modulus operator (%) and take modulus at 60 to get seconds in range 0-60.

const time = 450524354; // random time
const seconds = Math.floor(time / 1000) % 60;
console.log(seconds);

Convert milliseconds to minutes

To convert milliseconds to minutes divide it by 1000 * 60. Now, this is in minutes but has fractional value.

Use Math.floor to convert it to an integer.

Then use modulus operator (%) and take modulus at 60 to get minutes in range 0-60.

const time = 450524354; // random time
const minutes = Math.floor(time / (1000 * 60)) % 60;
console.log(minutes);

Similarly convert milliseconds to hours.

const time = 450524354; // random time
const hours = Math.floor(time / (1000 * 60 * 60)) % 60;
console.log(hours);

Similarly convert milliseconds to days.

const time = 450524354; // random time
const days = Math.floor(time / (1000 * 60 * 60 * 24)) % 24;
console.log(days);

JavaScript Code for countdown timer app

Since we have covered the concept of date object used here, let's see complete javascript code for countdown timer.

const comingYear = document.querySelector(".coming-year");
const birthDate = prompt("Enter birth date (1-31):");
const birthMonth = prompt("Enter birth month (1-12):");
const today = new Date();
var nextYear;
if (today.getMonth() + 1 > birthMonth || (today.getMonth() + 1 == birthMonth && today.getDate() + 1 > birthDate)) {
  nextYear = new Date().getFullYear() + 1;
}
else {
  nextYear = new Date().getFullYear();
}
comingYear.innerHTML = nextYear;
function countdown() {
  const remaining = new Date(\`\${nextYear}-\${birthMonth}-\${birthDate} 00:00:00\`) - new Date();
  const days = Math.floor(remaining / (1000 * 60 * 60 * 24));
  const hours = Math.floor(remaining / (1000 * 60 * 60)) % 24;
  const minutes = Math.floor(remaining / (1000 * 60)) % 60;
  const seconds = Math.floor(remaining / 1000) % 60;
  document.querySelector(".days").innerHTML = days;
  document.querySelector(".hours").innerHTML = hours;
  document.querySelector(".minutes").innerHTML = minutes;
  document.querySelector(".seconds").innerHTML = seconds;
}
countdown()
setInterval(countdown, 1000);

The above code of the countdown app takes 2 input from the user using the prompt date of birth and month of birth consecutively.

The date and month of birth are used to calculate if the birthday has gone this year or is in the same year.

Birthday is gone this year if following is true:

if (today.getMonth() + 1 > birthMonth ||
    (today.getMonth() + 1 == birthMonth &&
    today.getDate() + 1 > birthDate)
    ) {
  nextYear = new Date().getFullYear() + 1;
}
else {
  nextYear = new Date().getFullYear();
}

Then there is a javascript function which calculates remaining days, hours, minutes and seconds and injects the found data in the correct position in the HTML document using querySelector method.

Finally, the setInterval function repeatedly run the countdown function every 1000 milliseconds (1 second), which update remaining days, minutes, hours and seconds.


CSS Code for countdown timer app

Finally, use CSS to style the application to look fabulous.

Here is complete CSS code for the countdown timer and is discussed below.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: url('./birthday-cover.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

.countdown-timer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(to right, rgba(85, 85, 85, 0.6), rgba(199, 199, 199, 0.2))
}

ul li {
  display: inline-block;
  padding: 0 5px;
  font-family: sans-serif;
  text-align: center;
}

ul li span {
  display: block;
  font-size: 50px;
  padding-top: 5px;
  color: rgb(226, 206, 28);
  font-weight: 600;
}

ul li span:nth-child(2) {
  font-size: 20px;
}

.greet {
  color: rgb(211, 211, 211);
  font-size: 25px;
  text-align: center;
  font-family: sans-serif;
  margin-top: 30px;
}

.coming-year {
  font-size: 250px;
  font-weight: 900;
  color: rgba(255, 255, 255, 0.493);
}

@media (max-width:768px) {
  ul li span {
    font-size: 10vw;
  }

  ul li span:nth-child(2) {
    font-size: 15px;
  }

  .coming-year {
    font-size: 40vw;
    font-weight: 900;
  }
}

First, set browsers default margin and padding to 0 by selection all using *.

Second, set background image which you downloaded above to the body and set background-size: cover.

Third, use CSS flexbox to set the countdown app to the centre of the screen by selection class 'countdown-timer'.

Fourth, set <li> element inline-block this will make list element to position side by side.

Set other necessary CSS styles to make the app beautiful in your own way.

Finally use CSS media query to style elements for smaller device (max-width:768px).


Countdown timer complete code

Here is complete code for birtday countdown timer embeded in single HTML file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Countdown Timer</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      background: url('./birthday-cover.jpg');
      background-repeat: no-repeat;
      background-size: cover;
    }

    .countdown-timer {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background: linear-gradient(to right, rgba(85, 85, 85, 0.6), rgba(199, 199, 199, 0.2))
    }

    ul li {
      display: inline-block;
      padding: 0 5px;
      font-family: sans-serif;
      text-align: center;
    }

    ul li span {
      display: block;
      font-size: 50px;
      padding-top: 5px;
      color: rgb(226, 206, 28);
      font-weight: 600;
    }

    ul li span:nth-child(2) {
      font-size: 20px;
    }

    .greet {
      color: rgb(211, 211, 211);
      font-size: 25px;
      text-align: center;
      font-family: sans-serif;
      margin-top: 30px;
    }

    .coming-year {
      font-size: 250px;
      font-weight: 900;
      color: rgba(255, 255, 255, 0.493);
    }

    @media (max-width:768px) {
      ul li span {
        font-size: 10vw;
      }

      ul li span:nth-child(2) {
        font-size: 15px;
      }

      .coming-year {
        font-size: 40vw;
        font-weight: 900;
      }
    }
  </style>
</head>

<body>
  <div class="countdown-timer">
    <h1 class="greet">Timer To Your Next Birthday 🎂</h1>
    <ul>
      <li>
        <span class="days"></span>
        <span>DAYS</span>
      </li>
      <li>
        <span class="hours"></span>
        <span>HOURS</span>
      </li>
      <li>
        <span class="minutes"></span>
        <span>MINUTES</span>
      </li>
      <li>
        <span class="seconds"></span>
        <span>SECONDS</span>
      </li>
    </ul>
    <p class="coming-year"></p>
  </div>
  <script>
    const comingYear = document.querySelector(".coming-year");
    const birthDate = prompt("Enter birth date (1-31):");
    const birthMonth = prompt("Enter birth month (1-12):");
    const today = new Date();
    var nextYear;
    if (today.getMonth() + 1 > birthMonth || (today.getMonth() + 1 == birthMonth && today.getDate() + 1 > birthDate)) {
      nextYear = new Date().getFullYear() + 1;
    }
    else {
      nextYear = new Date().getFullYear();
    }
    comingYear.innerHTML = nextYear;
    function countdown() {
      const remaining = new Date(`\${nextYear}-\${birthMonth}-\${birthDate} 00:00:00`) - new Date();
      const days = Math.floor(remaining / (1000 * 60 * 60 * 24));
      const hours = Math.floor(remaining / (1000 * 60 * 60)) % 24;
      const minutes = Math.floor(remaining / (1000 * 60)) % 60;
      const seconds = Math.floor(remaining / 1000) % 60;
      document.querySelector(".days").innerHTML = days;
      document.querySelector(".hours").innerHTML = hours;
      document.querySelector(".minutes").innerHTML = minutes;
      document.querySelector(".seconds").innerHTML = seconds;
    }
    countdown()
    setInterval(countdown, 1000);
  </script>
</body>

</html>

Conclusion

We looked at few properties of Date object, how to get time and number of milliseconds ellapsed and then difference between 2 moments of time.

We also looked at how to use setInterval to update the countdown timer every second.

Then we worked on HTM, CSS and JavaScript code of Countdown timer app. We used prompt function to ask the user for birth date and birth month.