Stopwatch in JavaScript

Create a stopwatch

IntermediateDate/Time ProgramsExample 7 of 10
stopwatch.js
1// Method 1: Simple stopwatch
2class Stopwatch {
3 constructor() {
4 this.startTime = null;
5 this.elapsedTime = 0;
6 this.isRunning = false;
7 this.interval = null;
8 }
9
10 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 10ms
18 }
19 }
20
21 stop() {
22 if (this.isRunning) {
23 clearInterval(this.interval);
24 this.isRunning = false;
25 }
26 }
27
28 reset() {
29 this.stop();
30 this.elapsedTime = 0;
31 this.onUpdate();
32 }
33
34 onUpdate() {
35 const time = this.formatTime(this.elapsedTime);
36 console.log(time);
37 }
38
39 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);
44
45 return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${String(ms).padStart(2, '0')}`;
46 }
47
48 getTime() {
49 return this.elapsedTime;
50 }
51}
52
53const stopwatch = new Stopwatch();
54stopwatch.start();
55
56// Method 2: Stopwatch with laps
57class StopwatchWithLaps extends Stopwatch {
58 constructor() {
59 super();
60 this.laps = [];
61 }
62
63 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 }
72
73 getLaps() {
74 return this.laps;
75 }
76
77 reset() {
78 super.reset();
79 this.laps = [];
80 }
81}
82
83const lapStopwatch = new StopwatchWithLaps();
84lapStopwatch.start();
85// lapStopwatch.lap(); // Record lap
86
87// Method 3: Multiple stopwatches
88class MultiStopwatch {
89 constructor() {
90 this.stopwatches = new Map();
91 }
92
93 create(id) {
94 const sw = new Stopwatch();
95 this.stopwatches.set(id, sw);
96 return sw;
97 }
98
99 get(id) {
100 return this.stopwatches.get(id);
101 }
102
103 remove(id) {
104 const sw = this.stopwatches.get(id);
105 if (sw) sw.stop();
106 this.stopwatches.delete(id);
107 }
108}
109
110const 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