Dev.to WebDev 🛠 Dev 👁 1 📖 2 min read

Build a Countdown Timer App with JavaScript

A countdown timer is one of those small tools you end up using constantly: counting down to a product launch, an exam, a birthday, or a sale ending. In this post, we build one with plain JavaScript that takes a target da

A countdown timer is one of those small tools you end up using constantly: counting down to a product launch, an exam, a birthday, or a sale ending. In this post, we build one with plain JavaScript that takes a target date and shows days, hours, minutes, and seconds, updating every second.

The HTML is a date input and four boxes for the numbers:

<input type="datetime-local" id="target-date" />
<button id="start-btn">Start countdown</button>
<div id="countdown">
  <div><span id="days">0</span> days</div>
  <div><span id="hours">0</span> hours</div>
  <div><span id="minutes">0</span> minutes</div>
  <div><span id="seconds">0</span> seconds</div>
</div>

The logic is a setInterval that recomputes the difference between now and the target every second:

let timerId = null;

function startCountdown(target) {
  clearInterval(timerId);
  timerId = setInterval(() => {
    const diff = new Date(target) - new Date();

    if (diff <= 0) {
      clearInterval(timerId);
      document.getElementById('countdown').innerHTML = '<h2>Time is up!</h2>';
      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);

    document.getElementById('days').textContent = days;
    document.getElementById('hours').textContent = hours;
    document.getElementById('minutes').textContent = minutes;
    document.getElementById('seconds').textContent = seconds;
  }, 1000);
}

document.getElementById('start-btn').addEventListener('click', () => {
  const target = document.getElementById('target-date').value;
  if (target) startCountdown(target);
});

A few details make this nicer: save the target date in localStorage so the countdown survives a refresh, show a message when the countdown finishes, and pad single digits with a leading zero so the display looks clean. You can also add multiple named countdowns — one for an exam, one for a trip — by storing an array of targets instead of one.

A timer only helps if you use the time it counts down well. If you want to get better at that, the best time management books for beginners collect the systems that actually work — from planning your day in blocks to cutting the distractions that eat your hours.

This is a great beginner project because it teaches date math, intervals, and DOM updates in under 50 lines — and it produces a tool you will genuinely use.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.