Stopwatch in JavaScript
Create a stopwatch
IntermediateDate/Time ProgramsExample 7 of 10
stopwatch.js
1// Method 1: Simple stopwatch2class Stopwatch {3 constructor() {4 this.startTime = null;5 this.elapsedTime = 0;6 this.isRunning = false;7 this.interval = null;8 }910 start() {11 if (!this.isRunning) {12 this.startTime = Date.now() - this.elapsedTime;13 this.isRunning = true;14 this.interval = setInterval(() => {15 this.elapsedTime = Date.now() - this.startTime;16 this.onUpdate();17 }, 10); // Update every 10ms18 }19 }2021 stop() {22 if (this.isRunning) {23 clearInterval(this.interval);24 this.isRunning = false;25 }26 }2728 reset() {29 this.stop();30 this.elapsedTime = 0;31 this.onUpdate();32 }3334 onUpdate() {35 const time = this.formatTime(this.elapsedTime);36 console.log(time);37 }3839 formatTime(milliseconds) {40 const totalSeconds = Math.floor(milliseconds / 1000);41 const minutes = Math.floor(totalSeconds / 60);42 const seconds = totalSeconds % 60;43 const ms = Math.floor((milliseconds % 1000) / 10);4445 return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${String(ms).padStart(2, '0')}`;46 }4748 getTime() {49 return this.elapsedTime;50 }51}5253const stopwatch = new Stopwatch();54stopwatch.start();5556// Method 2: Stopwatch with laps57class StopwatchWithLaps extends Stopwatch {58 constructor() {59 super();60 this.laps = [];61 }6263 lap() {64 if (this.isRunning) {65 const lapTime = this.elapsedTime - (this.laps.length > 0 ?66 this.laps.reduce((sum, lap) => sum + lap, 0) : 0);67 this.laps.push(lapTime);68 console.log(`Lap ${this.laps.length}: ${this.formatTime(lapTime)}`);69 return lapTime;70 }71 }7273 getLaps() {74 return this.laps;75 }7677 reset() {78 super.reset();79 this.laps = [];80 }81}8283const lapStopwatch = new StopwatchWithLaps();84lapStopwatch.start();85// lapStopwatch.lap(); // Record lap8687// Method 3: Multiple stopwatches88class MultiStopwatch {89 constructor() {90 this.stopwatches = new Map();91 }9293 create(id) {94 const sw = new Stopwatch();95 this.stopwatches.set(id, sw);96 return sw;97 }9899 get(id) {100 return this.stopwatches.get(id);101 }102103 remove(id) {104 const sw = this.stopwatches.get(id);105 if (sw) sw.stop();106 this.stopwatches.delete(id);107 }108}109110const multi = new MultiStopwatch();111const sw1 = multi.create('timer1');112sw1.start();
Output
00:00:00 00:00:01 00:00:02
What's going on
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