Countdown Timer in JavaScript
Calculate remaining time until a target date in JavaScript with Date and a CountdownTimer class. Convert milliseconds to days and stop when the target expires.
Run in a browser console or with Node. The timers keep running until you stop them or close the process.
1// Method 1: Simple countdown2function countdown(targetDate, callback) {3 const interval = setInterval(() => {4 const now = new Date().getTime();5 const distance = targetDate.getTime() - now;67 if (distance < 0) {8 clearInterval(interval);9 callback({ expired: true });10 return;11 }1213 const days = Math.floor(distance / (1000 * 60 * 60 * 24));14 const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));15 const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));16 const seconds = Math.floor((distance % (1000 * 60)) / 1000);1718 callback({19 days,20 hours,21 minutes,22 seconds,23 total: distance24 });25 }, 1000);26}2728const target = new Date(Date.now() + 86400000); // 1 day from now29countdown(target, (time) => {30 if (time.expired) {31 console.log('Countdown expired!');32 } else {33 console.log(`${time.days}d ${time.hours}h ${time.minutes}m ${time.seconds}s`);34 }35});3637// Method 2: Countdown class38class CountdownTimer {39 constructor(targetDate, onUpdate, onComplete) {40 this.targetDate = targetDate;41 this.onUpdate = onUpdate;42 this.onComplete = onComplete;43 this.interval = null;44 }4546 start() {47 this.update();48 this.interval = setInterval(() => this.update(), 1000);49 }5051 stop() {52 if (this.interval) {53 clearInterval(this.interval);54 this.interval = null;55 }56 }5758 update() {59 const now = new Date().getTime();60 const distance = this.targetDate.getTime() - now;6162 if (distance < 0) {63 this.stop();64 if (this.onComplete) this.onComplete();65 return;66 }6768 const time = {69 days: Math.floor(distance / (1000 * 60 * 60 * 24)),70 hours: Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),71 minutes: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),72 seconds: Math.floor((distance % (1000 * 60)) / 1000),73 total: distance74 };7576 if (this.onUpdate) this.onUpdate(time);77 }7879 getRemaining() {80 const now = new Date().getTime();81 const distance = this.targetDate.getTime() - now;82 return distance > 0 ? distance : 0;83 }84}8586const timer = new CountdownTimer(87 new Date(Date.now() + 3600000), // 1 hour88 (time) => console.log(`${time.minutes}m ${time.seconds}s`),89 () => console.log('Timer complete!')90);91timer.start();
Sample Output
59m 59s
The class timer prints first because start() updates once right away.
0d 23h 59m 59s
Method 1 prints its first tick after one second.
In this one
- How to compute time left from two timestamps
- How to split milliseconds into days, hours, minutes and seconds
- How to stop a setInterval timer at expiry
- How a class bundles start, stop and callbacks
How it works
- 1
A target 1 day ahead is set for Method 1.
- 2
setInterval recalculates the distance every second.
- 3
The class timer for 1 hour starts and prints at once.
- 4
Each tick prints the remaining time.
- 5
When distance is negative, the interval is cleared and the complete message runs.
Edge cases
Timer never cleared
The interval keeps running after the page section is gone.
Call stop() or clearInterval when you are done.
Background tab
Ticks slow down to once per minute in some browsers.
Recompute from Date.now() each tick, as this code does.
Single digits
1h 5m 3s looks uneven in a big display.
Use String(n).padStart(2, '0') for 01:05:03.
What's going on
This date-math lesson uses Date and a CountdownTimer class to show the remaining time until a target date, such as an exam start.
The idea is simple. Every second, find the distance: target time minus now, in milliseconds. Then convert that number into days, hours, minutes and seconds.
The conversion uses division and the remainder operator %. Days are distance divided by the milliseconds in a day, rounded down. For hours, take the remainder after removing whole days, then divide by the milliseconds in an hour. Minutes and seconds follow the same pattern. Math.floor drops the decimal part.
Method 1 is a function. setInterval runs the update every 1000 ms. If the distance becomes negative, the target has passed. The code calls clearInterval to stop the timer and tells the callback { expired: true }. Handling expiry matters, or the timer would show negative numbers forever.
Method 2 wraps this in a CountdownTimer class. It takes a target date, an onUpdate callback for each tick, and an onComplete callback for the end. start() runs update once right away, so the screen is not blank for the first second, and then every second. stop() clears the interval. getRemaining() returns the milliseconds left, never below zero.
The output shows the class first because start() updates at once, while Method 1 waits one second for its first tick. Then both keep printing each second.
setInterval is not perfectly exact. Browsers can delay it, especially in background tabs. Because the code recomputes from the real time on every tick, the display corrects itself.
Best practices: clear the interval when the component is removed, handle expiry, format nicely with padStart, and consider pause and resume support.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What stops a setInterval?
Pick an answer to check it.
Question 2
What does a negative distance mean?
Pick an answer to check it.
Questions people ask
Why recompute from Date.now() instead of subtracting 1 each second?
Timers drift. Using the clock keeps it correct.
Does Method 1 show days?
Yes, as 0d while less than a day is left.
How do I add pause?
Save getRemaining() on pause, and set a new target from it on resume.