Stopwatch

Create a stopwatch

IntermediateTopic: Date/Time Programs
Back

JavaScript Stopwatch Program

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

Try This Code
// Method 1: Simple stopwatch
class Stopwatch {
    constructor() {
        this.startTime = null;
        this.elapsedTime = 0;
        this.isRunning = false;
        this.interval = null;
    }
    
    start() {
        if (!this.isRunning) {
            this.startTime = Date.now() - this.elapsedTime;
            this.isRunning = true;
            this.interval = setInterval(() => {
                this.elapsedTime = Date.now() - this.startTime;
                this.onUpdate();
            }, 10); // Update every 10ms
        }
    }
    
    stop() {
        if (this.isRunning) {
            clearInterval(this.interval);
            this.isRunning = false;
        }
    }
    
    reset() {
        this.stop();
        this.elapsedTime = 0;
        this.onUpdate();
    }
    
    onUpdate() {
        const time = this.formatTime(this.elapsedTime);
        console.log(time);
    }
    
    formatTime(milliseconds) {
        const totalSeconds = Math.floor(milliseconds / 1000);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        const ms = Math.floor((milliseconds % 1000) / 10);
        
        return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${String(ms).padStart(2, '0')}`;
    }
    
    getTime() {
        return this.elapsedTime;
    }
}

const stopwatch = new Stopwatch();
stopwatch.start();

// Method 2: Stopwatch with laps
class StopwatchWithLaps extends Stopwatch {
    constructor() {
        super();
        this.laps = [];
    }
    
    lap() {
        if (this.isRunning) {
            const lapTime = this.elapsedTime - (this.laps.length > 0 ? 
                this.laps.reduce((sum, lap) => sum + lap, 0) : 0);
            this.laps.push(lapTime);
            console.log(`Lap ${this.laps.length}: ${this.formatTime(lapTime)}`);
            return lapTime;
        }
    }
    
    getLaps() {
        return this.laps;
    }
    
    reset() {
        super.reset();
        this.laps = [];
    }
}

const lapStopwatch = new StopwatchWithLaps();
lapStopwatch.start();
// lapStopwatch.lap(); // Record lap

// Method 3: Multiple stopwatches
class MultiStopwatch {
    constructor() {
        this.stopwatches = new Map();
    }
    
    create(id) {
        const sw = new Stopwatch();
        this.stopwatches.set(id, sw);
        return sw;
    }
    
    get(id) {
        return this.stopwatches.get(id);
    }
    
    remove(id) {
        const sw = this.stopwatches.get(id);
        if (sw) sw.stop();
        this.stopwatches.delete(id);
    }
}

const multi = new MultiStopwatch();
const sw1 = multi.create('timer1');
sw1.start();
Output
00:00:00
00:00:01
00:00:02

Understanding Stopwatch

Stopwatch measures elapsed time.

Basic Stopwatch

Start/stop/reset
Track elapsed time
Format display
Update regularly

Lap Functionality

Record lap times
Calculate lap duration
Store lap history
Display laps

Features

Pause/resume
Reset
Format time
Multiple timers

Time Format

MM:SS.ms
Minutes:Seconds:Milliseconds
Pad with zeros

Use Cases

Sports timing
Performance measurement
Game timers
Productivity tracking

Best Practices

Use requestAnimationFrame for smooth updates
Clear intervals properly
Format time nicely
Handle edge cases

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 Stopwatch

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