Countdown Timer in JavaScript
Create a countdown timer
IntermediateDate/Time ProgramsExample 6 of 10
countdown-timer.js
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();
Output
23h 59m 59s 59m 59s
What's going on
Countdown timers show remaining time.
Implementation
Calculate time difference
Update every second
Format days/hours/minutes/seconds
Handle expiration
Countdown Class
Encapsulate logic
Start/stop methods
Update callback
Complete callback
Time Calculation
Total milliseconds
Convert to units
Handle negative (expired)
Use Cases
Event countdowns
Sale timers
Deadline reminders
Game timers
Best Practices
Clear interval on unmount
Handle expiration
Format nicely
Pause/resume support