TL;DR
To build a countdown timer in JavaScript, we save the moment it ends as a timestamp and, on every tick, compute the remaining time as that end time minus Date.now(). We round up to whole seconds, split them into days, hours, minutes, and seconds with Math.floor and %, and schedule each tick just after the next whole second.
- A countdown that subtracts 1 per setInterval callback drifts, because callbacks run late, busy pages skip them, and background tabs can slow them to once a second or even once a minute.
- Pausing saves the remaining milliseconds, and resuming sets a new end time of Date.now() plus what we saved, so the time spent paused never counts.
- new Date("2027-01-01") means midnight in UTC, so we use an explicit offset like 2027-01-01T00:00:00-08:00, or new Date(2027, 0, 1) for local midnight.
- The ticking number gets role="timer" and stays quiet, while a separate polite live region announces milestones like 10 seconds left and Time's up!
Countdown timers are everywhere. There is the "sale ends in" banner, the five minutes a quiz gives us, the egg timer on our phone, and the clock counting down to the ball drop in Times Square. Building one looks like a five-minute job: start at 10, subtract 1 every second, and stop at 0. That version works great right up until the page gets busy or we switch tabs, and then our countdown quietly falls behind the real clock.
In this tutorial, we are going to build a countdown timer in JavaScript that stays honest. It will count down a duration or count down to a calendar date, show days, hours, minutes, and seconds, and pause, resume, and reset. It will also keep screen reader users in the loop without chattering at them every second.
Onwards!
Meet Our Countdown Timer
Before we write any code, let's play with what we'll be building. The top countdown below counts down a duration, and the bottom one counts down to a date, which starts out as the next New Year's Day in your time zone:
Try it
- Press Start, then Freeze page 3 s
- Press Pause, wait, and press Resume
- Change the Ends at date and time
When we freeze the page, nothing moves for three seconds. Once the page wakes up, our countdown jumps straight to the right number. The Naive counter doesn't, and the Off by readout shows how far behind it fell. That gap is where we will start.
Why Does My setInterval Countdown Drift?
A setInterval countdown drifts because the 1000 we pass in is only a request. Callbacks run a little late, and while the page is busy, the ones that come due don't pile up, so some never run at all. If our code subtracts 1 per callback, each of those leaves our countdown further behind.
Here is the version most of us write first (our Timers in JavaScript tutorial covers setInterval if it is new to you):
let secondsLeft = 10;
const intervalID = setInterval(() => {
secondsLeft--;
display.textContent = secondsLeft;
if (secondsLeft === 0) {
clearInterval(intervalID);
}
}, 1000);
Our code counts callbacks and treats each one as exactly one second. Here is a 10-second countdown where each callback runs a few milliseconds late and the page gets busy for almost three seconds:
Callbacks were due around 3, 4, and 5 seconds, but the page was busy, so only one of them ran, at 5.203 seconds. Our counter showed 7 when the real answer was 5. When the real countdown hits 0, the counter still says 2.
Background tabs make this worse. To save battery, browsers slow down timers in tabs we aren't looking at (MDN's setTimeout page has the details). Firefox on the desktop runs them at most once per second. Chrome checks them once per second, and once a page has been hidden for more than 5 minutes and silent for 30 seconds, a chain of 5 or more timer calls gets checked just once per minute. That's a countdown losing 59 seconds every minute!
We can't make the browser run our callbacks on time, so we'll stop trusting them to measure time.
How Do We Keep a Countdown Accurate?
We store the moment our countdown ends as a timestamp, and on every tick, we compute the remaining time as that end time minus Date.now(). Because Date.now() reads the real clock, a late tick still gets the right answer. For a 10-second countdown, this looks as follows:
Date.now() is the number of milliseconds since January 1, 1970 (in UTC), which is why these numbers are so big. When we press Start, we add 10,000 to it and keep the result as our end time. A later tick asks for Date.now() again and subtracts, which leaves 6,400 milliseconds no matter how many callbacks ran late.
There is one tradeoff. Date.now() follows the computer's clock, so changing that clock mid-countdown moves our countdown too. performance.now() ignores clock changes and suits short stopwatch-style timers. For counting down to a real date, the computer's clock is what we want.
Turning Milliseconds into Days, Hours, Minutes, and Seconds
Milliseconds are great for math and terrible for reading. As I'm writing this, New Year's Day is 2,551,458,722 milliseconds away, which tells me...nothing useful. Our first step toward days, hours, minutes, and seconds is turning milliseconds into whole seconds:
We divide by 1,000 and round up to 2,551,459. Why up? Rounding down would make a fresh 10-second countdown show 9 the instant it starts, because a few milliseconds have already gone by. Rounding up shows 10 at the start and 0 only when time is truly up. From there, our seconds break down like making change, biggest coins first.
In code, Math.floor counts how many whole units fit, and the remainder operator (%) keeps what is left over (our tutorial on rounding numbers covers floor and ceil):
Look at the hours row. Our total has 708 whole hours, but 696 of them are already counted in our 29 days, so % 24 keeps the 12 that are left over. Minutes work the same way with % 60, and days need no wrap at all. As a function, this looks like the following:
function formatTime(ms) {
const totalSeconds = Math.ceil(ms / 1000);
return {
days: Math.floor(totalSeconds / 86400),
hours: Math.floor(totalSeconds / 3600) % 24,
minutes: Math.floor(totalSeconds / 60) % 60,
seconds: totalSeconds % 60
};
}
There is one more detail. When the seconds drop below 10, they turn into a single digit:
Our display shrinks from 0:10 to 0:9, and everything beside it shifts over. The padStart method fixes that by adding characters to the front of a string until it reaches the length we ask for:
function pad(number) {
return String(number).padStart(2, "0");
}
pad(9); // "09"
pad(44); // "44"
Our 9 becomes "09", and two-digit numbers are left alone. In CSS, font-variant-numeric: tabular-nums gives every digit the same width, so a skinny 1 doesn't wobble the display either.
Ticking Right After Each Second
Next up is deciding when to tick. Ticking every 1000 milliseconds seems obvious, but our display only changes when the remaining time crosses a whole second. If our ticks land right on top of those moments, a few milliseconds of lateness decide which side of the line each tick lands on:
In the top row, the tick at 3.004 seconds landed just past the 3-second line and showed 7, so 8 never appeared. The tick at 3.999 seconds landed just short of the 4-second line and showed 7 again. In the bottom row, each tick lands just after a whole second, so every number shows up exactly once.
The math for that is one line. The time until the next boundary is remaining % 1000 (or a full 1000 when we are sitting right on a boundary), and we add 20 milliseconds of cushion to land safely past it:
const delay = (remaining % 1000 || 1000) + 20;
timerID = setTimeout(tick, delay);
Each tick schedules the next one with setTimeout, so a late tick simply asks for a shorter wait. What about requestAnimationFrame? It would run our code around 60 times a second for a display that changes once a second, and browsers pause it in background tabs. It's a better fit for a smooth progress ring.
Stopping, Pausing, and Resetting
Our countdown can be in one of four states, and the buttons in our demo move it between them:
Reaching zero is the step that most often goes wrong. We clamp the remaining time with Math.max(0, ...) so it never goes negative (no -0:01!), we skip scheduling another tick, and we call our done action. Nothing else gets scheduled after that, so our done action runs exactly once.
Pausing needs a little help, because the clock keeps moving while we are paused. When we pause, we save the remaining milliseconds. When we resume, we compute a brand new end time:
We paused 3.65 seconds in and saved 6,350 milliseconds. Four seconds later, we resumed with an end time of now plus 6,350, so our countdown finished at 14 seconds of real time: 10 seconds of counting plus 4 seconds of waiting. Reset is the easy one. We clear the pending timer, go back to idle, and show the full duration again.
How Do We Count Down to a Specific Date?
We turn the date into a timestamp and use that as our end time, and everything else stays the same. The catch is creating the date correctly, because new Date("2027-01-01") does not mean midnight where you live:
A date-only string like "2027-01-01" is read as midnight in UTC (Coordinated Universal Time, the time zone with no offset). In Los Angeles, that's 4:00 PM on December 31, so a New Year's countdown there finishes 8 hours early, while Tokyo waits until 9:00 AM. Our demo's new Date readout shows what it means where you are. To avoid this, we say exactly what we mean:
// The same instant everywhere: midnight Pacific Time
const launch = new Date("2027-01-01T00:00:00-08:00");
// Midnight wherever the reader happens to be
const newYear = new Date(2027, 0, 1);
timer.until(launch.getTime());
The first one is an ISO 8601 string with an explicit offset of -08:00, so it is the same instant for everyone, which is what a product launch or a livestream needs. The second one uses local time, which fits New Year's Day (months start at 0 in the Date constructor, so 0 is January). A date and time with no offset, like "2027-01-01T00:00", is local time too, and that is how our demo reads its date picker. Where daylight saving time applies, the offset depends on the date, so double-check it or let a date library work it out.
Catching Up When the Tab Comes Back
Our clock-based countdown never drifts, but in a background tab, it can still be stale. If Chrome is only checking our timer once a minute, the number on screen can be almost a minute old when someone switches back. The fix is to tick right away when the visibilitychange event tells us our page is visible again:
document.addEventListener("visibilitychange", () => {
if (!document.hidden && timer.state === "running") {
timer.tick();
}
});
Calling tick early is perfectly safe. It computes everything from the end time, shows the right number, and lines the next tick back up with the next whole second.
Making It Work with Screen Readers
A countdown that changes every second can be a nightmare for someone using a screen reader. If we put aria-live on our ticking number, the screen reader will try to read every single second out loud. The better pattern keeps the number quiet and announces only the moments that matter:
Our number gets role="timer", which has an implicit aria-live value of off. Screen readers don't announce its changes, but people can still read it whenever they want. The announcements go in a separate, visually hidden element with aria-live="polite", which waits for the screen reader to finish talking before it speaks up:
<h2 id="eggTitle">Egg timer</h2>
<div id="display" role="timer" aria-labelledby="eggTitle">5:00</div>
<div id="announcer" class="visually-hidden" aria-live="polite"></div>
The Announced readout in our demo shows the latest announcement. With a screen reader on, our 1-minute countdown says "30 seconds left," "10 seconds left," and "Time's up!" and nothing in between.
Putting It All Together
Here is everything we've talked about in one reusable Countdown class, which is the same code that runs our demo:
class Countdown {
constructor({ onTick, onDone }) {
this.onTick = onTick;
this.onDone = onDone;
this.state = "idle";
this.endTime = 0;
this.remaining = 0;
this.timerID = null;
this.catchUp = () => {
if (!document.hidden && this.state === "running") {
this.tick();
}
};
document.addEventListener("visibilitychange", this.catchUp);
}
start(durationMs) {
this.until(Date.now() + durationMs);
}
until(endTime) {
this.endTime = endTime;
this.state = "running";
this.tick();
}
tick() {
clearTimeout(this.timerID);
const remaining = Math.max(0, this.endTime - Date.now());
this.onTick(remaining);
if (remaining === 0) {
this.state = "finished";
this.onDone();
return;
}
const delay = (remaining % 1000 || 1000) + 20;
this.timerID = setTimeout(() => this.tick(), delay);
}
pause() {
if (this.state !== "running") return;
clearTimeout(this.timerID);
this.remaining = Math.max(0, this.endTime - Date.now());
this.state = "paused";
}
resume() {
if (this.state !== "paused") return;
this.until(Date.now() + this.remaining);
}
reset() {
clearTimeout(this.timerID);
this.state = "idle";
}
destroy() {
this.reset();
document.removeEventListener("visibilitychange", this.catchUp);
}
}
Using it with our formatTime and pad functions and the markup from the previous section looks like this:
const display = document.querySelector("#display");
const announcer = document.querySelector("#announcer");
const milestones = [[60, "1 minute left"], [30, "30 seconds left"], [10, "10 seconds left"]];
let lastSeconds = null;
const timer = new Countdown({
onTick(remaining) {
const { minutes, seconds } = formatTime(remaining);
display.textContent = minutes + ":" + pad(seconds);
const secondsLeft = Math.ceil(remaining / 1000);
for (const [mark, words] of milestones) {
if (lastSeconds > mark && secondsLeft <= mark && secondsLeft > 0) {
announcer.textContent = words;
}
}
lastSeconds = secondsLeft;
},
onDone() {
announcer.textContent = "Time's up!";
}
});
timer.start(5 * 60 * 1000);
A few lines deserve a closer look:
- tick starts with clearTimeout, so when catchUp calls tick early, the tick that was already waiting gets canceled.
- The remaining === 0 check comes before we schedule anything, which is why onDone runs exactly once.
- resume just hands until a new end time of now plus the milliseconds we saved.
- Our milestone check looks for the moment we cross a mark instead of an exact match, so a skipped second can't swallow an announcement.
To count down to a date, we call timer.until(someDate.getTime()) instead of start. When our countdown is no longer needed, destroy cancels the pending tick and removes our listener.
Conclusion
Phew! A countdown timer turns out to be a bit more than subtracting 1 every second. The big idea is to let the clock keep time and use our timer callbacks only as reminders to go look at it. We keep one number, the end time, and everything else (formatting, pausing, stopping at zero, catching up, and announcing milestones) builds on it.
There is one limitation to be honest about. Our countdown is only as right as the clock on the computer running it, and some clocks are off by a minute or more. When a few seconds really matter, like in an auction or an exam, the server should decide when time is up. For egg timers and New Year's Eve, you are all set. Happy counting!
Before you go, here are a few things you can do:
-
Keep reading
Read the next article in the series, Variable Scope, or check out some related content:
-
Ask a question
Stuck on something, or curious about a detail we skipped? Ask on the forums, and we’ll help you out.
Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.
Your support keeps this site going! 😇











