JavaScript Countdown Timer

A countdown shows the time left until a date, such as a sale end or an event. We use setInterval() to update it every second.

HTML and JavaScript

<p id="countdown"></p>

<script>
  const target = new Date("2030-01-01T00:00:00").getTime();
  const el = document.getElementById("countdown");

  const timer = setInterval(() => {
    const diff = target - Date.now();

    if (diff <= 0) {
      clearInterval(timer);
      el.textContent = "Time is over!";
      return;
    }

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

    el.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;
  }, 1000);
</script>

Output in the browser (the numbers change every second; this is one example):

Output in the browser

1234d 5h 42m 17s

How it works

  • target - Date.now() is the time left in milliseconds.
  • We divide by 1000 (seconds), 60 (minutes), 60 (hours) and 24 (days), and use % to keep only the part that belongs to each unit.
  • When the time is over, clearInterval() stops the timer.

Related: JavaScript Date and Callbacks and Promises.


Learn more about the similar topics:
Tutorials
JavaScript Events
JavaScript HTML DOM
JavaScript DOM Manipulation
JavaScript HTML DOM EventListener
JavaScript Forms and Validation
Exercises & Assignments
Write a JavaScript program to change the text of a paragraph on button click
Write a JavaScript program to switch dark mode on and off
Interview Questions & Answers
What is the DOM in JavaScript?
How do you select elements in the DOM?
What are events and event listeners in JavaScript?
What is event bubbling and capturing in JavaScript?
What is event delegation in JavaScript?