Learn to code and change your life

Whether you want to sign up for our coding courses, get more information, hire our students, or just have a chat with us, we’re looking forward to hearing from you!

Book a Call With Us Find out more

How to – JavaScript Countdown Timer

How to - JavaScript Countdown Timer

Creating a Countdown Timer

To create a countdown timer, we’ll use JavaScript to calculate the time difference between the current date and the target date. We’ll then update the timer every second to display the remaining time in days, hours, minutes, and seconds.


Example

Here’s an example of a countdown timer that counts down to a specific date and time:

<!-- Display the countdown timer in an element -->
<p id="demo"></p>

<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2030 15:37:25").getTime();

// Update the countdown every 1 second
var x = setInterval(function() {
  // Get today's date and time
  var now = new Date().getTime();
  
  // Calculate the distance between now and the target date
  var distance = countDownDate - now;
  
  // Calculate days, hours, minutes, and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  
  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
  
  // If the countdown is over, display "EXPIRED"
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

How It Works

  1. Set the Target Date:
    We define the target date and time using new Date("Jan 5, 2030 15:37:25"). The getTime() method converts this date into a timestamp in milliseconds.

  2. Update the Timer Every Second:
    We use setInterval to update the timer every second (1000 milliseconds).

  3. Calculate the Remaining Time:

    • Subtract the current time (now) from the target time (countDownDate) to get the time difference (distance).

    • Convert the difference into days, hours, minutes, and seconds using simple math operations.

  4. Display the Timer:
    The calculated time is displayed in an HTML element with the ID demo.

  5. Handle Expiration:
    If the countdown reaches zero (or goes negative), the timer stops, and the text “EXPIRED” is displayed.