Countdown Timer in JavaScript

Create a countdown timer

IntermediateDate/Time ProgramsExample 6 of 10
countdown-timer.js
1// Method 1: Simple countdown
2function countdown(targetDate, callback) {
3 const interval = setInterval(() => {
4 const now = new Date().getTime();
5 const distance = targetDate.getTime() - now;
6
7 if (distance < 0) {
8 clearInterval(interval);
9 callback({ expired: true });
10 return;
11 }
12
13 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);
17
18 callback({
19 days,
20 hours,
21 minutes,
22 seconds,
23 total: distance
24 });
25 }, 1000);
26}
27
28const target = new Date(Date.now() + 86400000); // 1 day from now
29countdown(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});
36
37// Method 2: Countdown class
38class CountdownTimer {
39 constructor(targetDate, onUpdate, onComplete) {
40 this.targetDate = targetDate;
41 this.onUpdate = onUpdate;
42 this.onComplete = onComplete;
43 this.interval = null;
44 }
45
46 start() {
47 this.update();
48 this.interval = setInterval(() => this.update(), 1000);
49 }
50
51 stop() {
52 if (this.interval) {
53 clearInterval(this.interval);
54 this.interval = null;
55 }
56 }
57
58 update() {
59 const now = new Date().getTime();
60 const distance = this.targetDate.getTime() - now;
61
62 if (distance < 0) {
63 this.stop();
64 if (this.onComplete) this.onComplete();
65 return;
66 }
67
68 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: distance
74 };
75
76 if (this.onUpdate) this.onUpdate(time);
77 }
78
79 getRemaining() {
80 const now = new Date().getTime();
81 const distance = this.targetDate.getTime() - now;
82 return distance > 0 ? distance : 0;
83 }
84}
85
86const timer = new CountdownTimer(
87 new Date(Date.now() + 3600000), // 1 hour
88 (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