John Mwaniki /   18 Jul 2023

How to Make a Countdown Timer using jQuery

In this article, you will learn how to make a countdown timer on your web page using jQuery in a step-by-step process.

A countdown timer is a visual representation of the time remaining until a specified event or deadline.

It typically consists of digits ticking down to zero, accompanied by labels for days, hours, minutes, and seconds.

Countdown timers are commonly used in:

  • Product launches:  This is done to build excitement and anticipation for a new release.
  • Event registration: It encourages users to sign up before time runs out.
  • Limited-time offers: This prompts customers to make a purchase with a sense of urgency.
  • Time-sensitive promotions: Drives engagement by highlighting time-limited discounts.
  • Time-bound online exams: Keep the student updated on the remaining duration before the exam time is over.

Creating a Countdown Timer with jQuery

To create a countdown timer using jQuery, we'll use HTML for structure, CSS for styling, and jQuery for dynamic functionality. Here's a breakdown of the process:

Step 1: Set up the HTML structure

First, we will create a basic HTML structure for the page with an element that will contain our countdown timer.

<!DOCTYPE html>
<html>
<head>
<title>Countdown Timer</title>
</head>
<body>
<div id="countdown"></div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</body>
</html>

In this code snippet, we have a <div> element with the ID "countdown" that will serve as the container for our timer. We also include a reference to the jQuery library.

Step 2: Style the countdown timer

Apply CSS styling to make the countdown timer visually appealing and to have the look and feel of your liking.

#countdown {
  background: #dcdcdc;
  color: #3e058e;
  width: 80%;
  padding: 35px;
  border-radius: 8px;
  font-size: 40px;
  font-weight: bold;
  text-align: center;
  margin: 30px auto;
}

Step 3: Implementing the Countdown Timer Logic in jquery

Using jQuery, we define the event/target date and time and get the current date and time.

var endDate = new Date("2023-12-31T23:59:59").getTime();
var dateTimeNow = new Date().getTime();

We then calculate the time difference by subtracting the two dates.

var remainingTime = endDate - dateTimeNow;

The time difference is in milliseconds since the JS getTime() function returns the number of milliseconds since the Unix Epoch.

Now that we have the amount of time remaining, the next task is to get the number of days, hours, minutes, and seconds from it.

We start from the highest time unit to the lowest (in this case, from days to seconds). This is done by dividing the time difference by the number of milliseconds that make each time unit and then rounding down the result using the Math.floor() function.

The remainder of the division is then divided by the number of milliseconds that makes up the lower time unit and so on repeatedly to the lowest unit.

A day is made of 24 hours, an hour is made up of 60 minutes, a minute is made up of 60 seconds, and a second is made up of 1,000 milliseconds. So for example, to get the number of days remaining, we have to divide the time difference by (1000*60*60*24) and so on for the other time units.

var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

The percent % sign, known as the modulus operator helps us to get the remainder of the division from the higher time units to work with in the lower unit calculation.

Now that we have the time difference in various units stored in variables, the next step is to update the countdown div with these variables accordingly using the .html() or .text() functions. This is together with the time labels to indicate each time unit.

$("#countdown").html(days + "days " + hours + "hrs " + minutes + "min " + seconds + "s");

The "#countdown" is the ID of our countdown div and that is why we are using it as the selector to target the element. You case use a different selector if your div/element has a different one or even use the tag name or its class name.

Since the current time keeps changing and the essence of a countdown timer is to update the remaining time as frequently as possible (typically after every second), we need to automate the updating process using the setInterval() function.

Syntax

setInterval(function, timeInterval)

The first argument specifies the function to be executed. This function should contain all our logic for calculating the time remaining, converting it to different units, and updating it in the countdown div.

The second argument should be a number specifying the time intervals in milliseconds after which the function should be executed. To set it to one second, we pass the value 1000.

var endDate = new Date("2023-12-31T23:59:59").getTime();

  setInterval(function() {
    var dateTimeNow = new Date().getTime();
    var remainingTime = endDate - dateTimeNow;

    var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
    var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

    $("#countdown").html(days + "days " + hours + "hrs " + minutes + "min " + seconds + "s");
  }, 1000);

The above code works perfectly and the time remaining in days, hours, minutes, and seconds keeps ticking down after every second. However, after the target date is reached, the countdown will continue ticking to negative values.

We need to stop the countdown and show some text such as "Time is up!" or "Expired" after the target date and time is reached.

To do so, we need to check if the remaining time is less than 0. If so, we use the clearInterval() function to stop the setInterval() function and then update the value of the countdown div with our preferred text.

We can achieve this by assigning the setInterval() function to a variable and then passing that variable to the clearInterval() function then updating the div text the same way we did above.

Full jQuery example:

$(function(){
  var endDate = new Date("2023-12-31T23:59:59").getTime();

  var countdown = setInterval(function() {
    var dateTimeNow = new Date().getTime();
    var remainingTime = endDate - dateTimeNow;

    var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
    var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

    $("#countdown").html(days + "days " + hours + "hrs " + minutes + "min " + seconds + "s");

    if (remainingTime < 0) {
      clearInterval(countdown);
      $("#countdown").html("Time is up!");
    }
  }, 1000);
});

Complete working countdown timer example code in HTML, jQuery, and CSS.

<!DOCTYPE html>
<html>
<head>
<title>Countdown Timer</title>
<style>
#countdown {
  background: #dcdcdc;
  color: #3e058e;
  width: 80%;
  padding: 35px;
  border-radius: 8px;
  font-size: 40px;
  font-weight: bold;
  text-align: center;
  margin: 30px auto;
}
</style>
</head>
<body>
<div id="countdown"></div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
$(function(){
  var endDate = new Date("2023-12-31T23:59:59").getTime();

  var countdown = setInterval(function() {
    var dateTimeNow = new Date().getTime();
    var remainingTime = endDate - dateTimeNow;

    var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
    var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

    $("#countdown").html(days + "days " + hours + "hrs " + minutes + "min " + seconds + "s");

    if (remainingTime < 0) {
      clearInterval(countdown);
      $("#countdown").html("Time is up!");
    }
  }, 1000);
});
</script>
</body>
</html>

Play around with the above code, changing the units of time measurements, updating time intervals, and CSS styling to your own liking and preference.

That's it!

Now you know how to make a countdown timer on your web pages using jQuery.