Countdown Timer

Create a countdown timer

IntermediateTopic: Date/Time Programs
Back

JavaScript Countdown Timer Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// 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.

Practical Learning Notes for Countdown Timer

This JavaScript program is part of the "Date/Time Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents