Countdown Timer
Create a countdown timer
IntermediateTopic: Date/Time Programs
JavaScript Countdown Timer Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Simple countdown
function countdown(targetDate, callback) {
const interval = setInterval(() => {
const now = new Date().getTime();
const distance = targetDate.getTime() - now;
if (distance < 0) {
clearInterval(interval);
callback({ expired: true });
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
callback({
days,
hours,
minutes,
seconds,
total: distance
});
}, 1000);
}
const target = new Date(Date.now() + 86400000); // 1 day from now
countdown(target, (time) => {
if (time.expired) {
console.log('Countdown expired!');
} else {
console.log(`${time.days}d ${time.hours}h ${time.minutes}m ${time.seconds}s`);
}
});
// Method 2: Countdown class
class CountdownTimer {
constructor(targetDate, onUpdate, onComplete) {
this.targetDate = targetDate;
this.onUpdate = onUpdate;
this.onComplete = onComplete;
this.interval = null;
}
start() {
this.update();
this.interval = setInterval(() => this.update(), 1000);
}
stop() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
update() {
const now = new Date().getTime();
const distance = this.targetDate.getTime() - now;
if (distance < 0) {
this.stop();
if (this.onComplete) this.onComplete();
return;
}
const time = {
days: Math.floor(distance / (1000 * 60 * 60 * 24)),
hours: Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((distance % (1000 * 60)) / 1000),
total: distance
};
if (this.onUpdate) this.onUpdate(time);
}
getRemaining() {
const now = new Date().getTime();
const distance = this.targetDate.getTime() - now;
return distance > 0 ? distance : 0;
}
}
const timer = new CountdownTimer(
new Date(Date.now() + 3600000), // 1 hour
(time) => console.log(`${time.minutes}m ${time.seconds}s`),
() => console.log('Timer complete!')
);
timer.start();Output
23h 59m 59s 59m 59s
Understanding Countdown Timer
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
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.