DEV Community

Cover image for How to build a countdown timer with JavaScript
Aliyu Adeniji
Aliyu Adeniji

Posted on

How to build a countdown timer with JavaScript

Introduction

Countdown timers web components or functions that are used in websites to create notifications of deadlines and events, they're are most commonly used in e-commerce and event management websites to create awareness and urgency about events that are set to occur in future dates. They're also used to motivate product users to take actions before the deadline of the events.

In this tutorial, we will learn how to create a simple countdown timer with Javascript, as usual, we will create a simple HTML project for our app, with some CSS styling to make our project appealing, and finally, we will add JavaScript to make our project functional. By the end of this tutorial, you will have a fully functional countdown timer that you can integrate into your next
launching event.

To get started, create a simple HTML document, with a code editor of your choice, and name it index.html, in the HTML document, create a digital time counter that will be modified using JavaScript in this tutorial similar to the following illustration.

javascript

Once our project is ready with some styling, we can start adding the functionalities.
Since we are dealing with dates in our project, it will be useful to create an array of months and weekdays that are going to be useful while building our countdown timer, let's go ahead and create two arrays; one for the months of the year and the other for days of the week as follows;



const months = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];


Enter fullscreen mode Exit fullscreen mode


const weekdays = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];


Enter fullscreen mode Exit fullscreen mode

The first step is to select the parts of our project that we are going to be changing dynamically using javascript in the following steps;
Select the h4 element with the class of launching which will serve as a header text that bares the launching date of our JavaScript and
const launching = document.querySelector(“.launching”);
Select the launch-container element that will display a launch message once the launch date has arrived.
const launch = document.querySelector(“.launch-container”);
Select the time container that can be used to select the h4 elements containing the times that are changing as the launch approaches, these h4 elements are nested in the div element with the class time container.
const items = document.querySelectorsAll(“.time-format”);

The next step is to set a variable called futureDate that will be our launch date and which we are going to work with in this tutorial, then pass a particular date into the variable in the order of year, month, day, time in hour, minutes, and seconds.

Let futureDate = new Date(2030, 5, 20, 9, 45, 0);
Then, we extract the values of the date we passed into our futureDate variable in order to be able to use them independently.



const year = futureDate.getFullYear();
let date = futureDate.getDate();
const year = futureDate.getFullYear();
const hour = futureDate.getHours();
const mins = futureDate.getMinutes();
const secs = futureDate.getSeconds();


Enter fullscreen mode Exit fullscreen mode

We set the day and month into a reusable variable in order to select the month and day from our month and weekdays array above.



  let day = futureDate.getDay();
  day = weekdays[day];


Enter fullscreen mode Exit fullscreen mode


  let month = futureDate.getMonth();
  month = months[month];


Enter fullscreen mode Exit fullscreen mode

After extracting the details of our futureDate, we can set our launch date dynamically to a template string using the JavaScript textContent function with the following syntax:



launching.textContent = `Launching is on ${day} ${date} ${month} ${year} at ${hour}:${mins}am`;


Enter fullscreen mode Exit fullscreen mode

The launch date will automatically be updated to our set future date as seen below.

countdown

Other variables that we will make use of are the future date in milliseconds and the present date in milliseconds, then, we get hold of the difference between both dates using the following syntax:
const remainingDate = futureDate-todayDate;
This syntax will return the difference in the dates in milliseconds, use consle.log to check this. Since our dates are now in milliseconds, we need to convert the milliseconds into days, hours, minutes, and seconds to be displayed on our counter. The conversion is done as illustrated below;



   1s = 1000ms
   1m = 60s
   1hr = 60m
   1d = 24hr
  // values in miliseconds
  const oneDay = 24 * 60 * 60 * 1000;
  const oneHour = 60 * 60 * 1000;
  const oneMinute = 60 * 1000;


Enter fullscreen mode Exit fullscreen mode

calculate all the values and use Math.floor to convert the values into whole numbers.



let days = remainingDate / oneDay;
days = Math.floor(days);
let hours = Math.floor((remainingDate % oneDay) / oneHour);
let minutes = Math.floor((remainingDate % oneHour) / oneMinute);
let seconds = Math.floor((remainingDate % oneMinute) / 1000);


Enter fullscreen mode Exit fullscreen mode

This difference will be used in a getRemainingTime function that will be called every second until the launch date has arrived, once the launch date has arrived, the function will be called and the launch message will be displayed on our project page.

The next step is to create a getRemainingTime Function for our countdown timer, this function will also be invoked immediately after the function’s body separately, to display the launch message once its launching time as shown below, also, in this function we need to set an array of values that will correspond to the days, hours, minutes and seconds in our countdown timer, this values array will be matched with our items variable holding the h4 elements that contain our timer container



 function getRemainingTime() {
            const todayDate = new Date()
            const remainingDate = futureDate - todayDate;
            let days = remainingDate / oneDay;

            days = Math.floor(days);

            let hours = Math.floor((remainingDate % oneDay) / oneHour);
            let minutes = Math.floor((remainingDate % oneHour) / oneMinute);
            let seconds = Math.floor((remainingDate % oneMinute) / 1000);
            const values = [days, hours, minutes, seconds];

            function format(item) {
                if (item < 10) {
                    return (item = `0${item}`)
                }
                return item
            }

            items.forEach(function (item, index) {
                item.innerHTML = format(values[index]);
            });

            if (remainingDate < 0) {
                clearInterval(countdown);
                launching.innerHTML = `<h4> Lauching has started</h4>`
            }
        }
        let countdown = setInterval(getRemainingTime, 1000);
        getRemainingTime()


Enter fullscreen mode Exit fullscreen mode

Save this and your timer will be updated to the exact remaining time to your launch date.
Since we are building a countdown timer, we need to make sure that the time on our screen is automatically updated every second and we do this by setting a new variable called countdown, using the setInterval function just above the getRemainingTime().



let countdown = setInterval(getRemainingTime(), 1000);


Enter fullscreen mode Exit fullscreen mode

In the getRemainingTime() function, we need to control the timer to display the launch message when the remainaingDate() is less than zero, we can do this using the following syntax inside the getRemainingTime() function:



If (remainaingDate<0){
  clearInterval(countdown);
  deadline.innerHTML = `<h4> Lauching has started</h4>`
  }


Enter fullscreen mode Exit fullscreen mode

We use the clearInterval to stop the setInterval that is automatically updating our counter every second since our Launchdate has arrived.

Conclusion
Building a countdown timer with JavaScript is a useful and practical skill for any developer. With just a few lines of code, you can create a countdown timer that accurately counts down to a specific date and time, and can be customized to fit your needs. By following the steps outlined in this tutorial, you should have a countdown timer that you can incorporate into your next Launch, and be able to add more advanced features as needed.

Top comments (0)