# Building a Countdown Timer in JavaScript by [kirupa](https://www.kirupa.com/me/index.htm) | filed under [JavaScript 101](https://www.kirupa.com/javascript/learn_javascript.htm) **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: Interactive example: [Two countdowns. The first counts down 10 seconds, 1 minute, or 5 minutes with Start, Pause, Resume, Reset, and Freeze page buttons, plus readouts for a naive counter and how far off it is. The second counts down to a date and time you pick, showing days, hours, minutes, and seconds](https://www.kirupa.com/html5/examples/countdown_timer_lab.htm) **Try it:** 1. Press **Start**, then **Freeze page 3 s** 2. Press **Pause**, wait, and press **Resume** 3. 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](https://www.kirupa.com/html5/timers_js.htm) tutorial covers `setInterval` if it is new to you): ```js 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: [](https://www.kirupa.com/html5/images/cd_drift.png?v=a786b2981338) 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](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#reasons_for_longer_delays_than_specified) 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: [](https://www.kirupa.com/html5/images/cd_end_time.png?v=09a2dbc510c1) `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: [](https://www.kirupa.com/html5/images/cd_breakdown.png?v=dbb312e39117) 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](https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm) covers `floor` and `ceil`): [](https://www.kirupa.com/html5/images/cd_modulo.png?v=01b28effe590) 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: ```js 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: [](https://www.kirupa.com/html5/images/cd_padstart.png?v=20f92e61f97b) 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: ```js 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: [](https://www.kirupa.com/html5/images/cd_tick_alignment.png?v=78cbcb141dfa) 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: ```js 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](https://www.kirupa.com/html5/animating_with_requestAnimationFrame.htm)? 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: [](https://www.kirupa.com/html5/images/cd_states.png?v=1c2d95153869) 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: [](https://www.kirupa.com/html5/images/cd_pause.png?v=a2e4ac188d2e) 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: [](https://www.kirupa.com/html5/images/cd_utc_gotcha.png?v=f06ba4ecc8b6) 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: ```js // 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: ```js 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: [](https://www.kirupa.com/html5/images/cd_announcements.png?v=3844880f3434) 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: ```markup