Stopwatch in JavaScript

Measure elapsed time in JavaScript with Date.now and a Stopwatch class. Format durations, resume saved time, and record laps; interval ticks can be delayed.

IntermediateJavaScript Date and Time ProgramsExample 7 of 10

Run in a browser console or Node. Each running stopwatch prints every 10 ms, so stop them when you have seen enough.

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();

Sample Output

00:00.01 (three times)

Three stopwatches are running, so each tick prints three lines.

In this one

  • How start time minus elapsed time enables pause and resume
  • How to format milliseconds as MM:SS.ms
  • How to record laps with a subclass
  • How to manage several timers with a Map

How it works

  1. 1

    stopwatch.start() begins logging every 10 ms.

  2. 2

    lapStopwatch starts too, ready for lap().

  3. 3

    multi.create("timer1") makes a third stopwatch and starts it.

  4. 4

    Each tick prints the elapsed time from all three.

  5. 5

    stop(), reset() and lap() can be called at any time.

Edge cases

Pressing start twice

A second interval would double the updates.

The isRunning check ignores the second start.

Long runs

After 60 minutes the format shows 60:00.00 and keeps counting minutes.

Add an hours part if you need it.

Console spam

Three timers logging every 10 ms flood the console.

Stop them, or update a page element instead of logging.

What's going on

This elapsed-time lesson uses Date.now and a Stopwatch class to count up from zero. Students use one to time a lab experiment or a speed-typing test.

Method 1 is the Stopwatch class. It stores startTime, elapsedTime, an isRunning flag and the interval id.

start() only runs if the stopwatch is stopped. It sets startTime to Date.now() - elapsedTime. That subtraction is the trick that makes pause and resume work. If you already had 5 seconds, the start time is moved 5 seconds back, so the count continues from 5. Then setInterval updates elapsedTime every 10 ms and calls onUpdate.

stop() clears the interval and sets isRunning to false. reset() stops it, sets elapsed time back to 0, and shows 00:00.00.

formatTime turns milliseconds into MM:SS.ms. It finds total seconds, then minutes and leftover seconds, then hundredths of a second. padStart adds leading zeros.

Method 2 extends Stopwatch with laps. A lap is the time since the last lap. lap() subtracts the sum of previous laps from the total elapsed time, saves it, and prints it. reset() also clears the laps by calling super.reset() first.

Method 3 manages several stopwatches in a Map, keyed by id, with create, get and remove. remove() stops a stopwatch before deleting it.

The code starts three stopwatches at once, so you see three lines for every tick. Elapsed time comes from Date.now(), not from counting ticks, so it stays accurate even if the interval is late.

For a smooth on-screen display, requestAnimationFrame is a good alternative to a 10 ms interval. Best practices: clear intervals properly, format time nicely and handle edge cases like pressing start twice.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why does start() use Date.now() - elapsedTime?

Pick an answer to check it.

Question 2

What does formatTime(61500) return?

Pick an answer to check it.

Questions people ask

Why update every 10 ms?

The display shows hundredths of a second, which change every 10 ms.

Why use Date.now() instead of counting ticks?

Intervals can run late. The clock is always right.

How do I record a lap?

Call lapStopwatch.lap() while it is running.