Countdown Timer JavaScript

A simple countdown timer that counts down from a set time and stops at zero, useful for timed actions like redirects.


Script Title: Countdown Timer
Description: A JavaScript countdown timer that counts down from a set time and stops at zero. Useful for redirects, notifications, and timed user interactions.

Live Example

Default: 30 seconds. Try changing the start value.

No libraries

Time remaining
00:30

Modern countdown timer snippet (recommended)

Clean, accessible, and easy to customize. Add your redirect or action inside onDone().

<div id="countdown" aria-live="polite">00:30</div>

<script>
(function () {
  function pad(n) { return String(n).padStart(2, '0'); }
  function format(seconds) {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return pad(m) + ':' + pad(s);
  }

  function startCountdown(opts) {
    const el = document.getElementById(opts.elementId);
    let remaining = Math.max(0, Number(opts.startSeconds) || 0);
    let t = null;

    function render() { el.textContent = format(remaining); }
    function stop() { if (t) clearInterval(t); t = null; }
    function done() {
      stop();
      if (typeof opts.onDone === 'function') opts.onDone();
    }

    render();
    t = setInterval(() => {
      remaining -= 1;
      if (remaining <= 0) { remaining = 0; render(); done(); return; }
      render();
    }, 1000);

    return { stop };
  }

  startCountdown({
    elementId: "countdown",
    startSeconds: 30,
    onDone: function () {
      // Example redirect:
      // window.location.href = "https://example.com";
    }
  });
})();
</script>

FAQ

Set startSeconds in the modern snippet. For example, 60 equals 1 minute.

Yes. Add your code inside onDone(), such as a redirect, message, or enabling a button.

Yes. It is plain JavaScript and does not require jQuery or any external libraries.