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.

Table of Contents