How to Build a Stopwatch with Lap Times in React
If a stopwatch saves the "time since the last press" each time you press lap, the laps may not add up to the running total after truncating to the display precision. If you store only the running total at the moment of each press, truncate it to the display unit (1/100 second), and then subtract, the laps in the table always add up to the displayed running total.
Here I build a useStopwatch hook that supports start, stop, resume, lap, and reset, along with a component that renders the lap table.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc and then transformed them with esbuild. To check the on-screen behavior, I stopped the clock with Playwright's clock API (page.clock) and pressed the buttons at set times. page.clock also replaces Date, performance.now(), and requestAnimationFrame. Only the check that pressed Lap eight times at about 0.3-second intervals ran in real time without controlling the clock. The development build with StrictMode produced the same output as the production build, and neither printed any errors or warnings to the console. I did not test Firefox or Safari, or what happens when the tab is moved to the background.

Calculating elapsed time from the start time
While the watch is running, the state holds the time it was started (startedAt), not the elapsed time itself. When the watch stops, the time measured so far is added to base. The elapsed time is calculated on each render by adding base to the difference between the start time and the current time.
import { useEffect, useState } from 'react';
type Watch = {
running: boolean;
base: number; // total time measured before stopping (ms)
startedAt: number; // time when the watch was started (performance.now())
splits: number[]; // running total at the moment each lap was pressed (ms)
};
const initial: Watch = { running: false, base: 0, startedAt: 0, splits: [] };
export function useStopwatch() {
const [watch, setWatch] = useState<Watch>(initial);
const [now, setNow] = useState(0);
// While running, refresh the current time on every frame
useEffect(() => {
if (!watch.running) return;
let id = requestAnimationFrame(function tick() {
setNow(performance.now());
id = requestAnimationFrame(tick);
});
return () => cancelAnimationFrame(id);
}, [watch.running]);
const elapsed = watch.running ? watch.base + Math.max(0, now - watch.startedAt) : watch.base;
const start = () => {
if (watch.running) return;
const t = performance.now();
setNow(t);
setWatch({ ...watch, running: true, startedAt: t });
};
const stop = () => {
if (!watch.running) return;
setWatch({ ...watch, running: false, base: watch.base + performance.now() - watch.startedAt });
};
// Compute the total at the moment of the press. Also sync now (the value on screen can be up to one frame old)
const lap = () => {
if (!watch.running) return;
const t = performance.now();
setNow(t);
setWatch({ ...watch, splits: [...watch.splits, watch.base + t - watch.startedAt] });
};
const reset = () => {
setWatch(initial);
setNow(0);
};
return { running: watch.running, elapsed, splits: watch.splits, start, stop, lap, reset };
}
I used performance.now() rather than Date.now(). According to MDN's explanation of performance.now(), Date.now() can be affected by adjustments to the system clock, such as time synchronization. performance.now() is based on a clock that only moves forward and is not affected by such adjustments. It also returns values finer than 1 millisecond.
For triggering redraws, I used requestAnimationFrame. As described in MDN's requestAnimationFrame explanation, the callback is usually called in sync with the display's refresh rate. Because the display shows 1/100-second digits, redrawing in step with screen updates suits this better than redrawing at a fixed interval with setInterval. The callback only updates the current time with setNow, and the elapsed time is recalculated from the difference with startedAt. Even if the callbacks are called at uneven intervals, the displayed time does not drift.
When stopping sets watch.running to false, the cleanup function returned from useEffect calls cancelAnimationFrame, and the redraws stop. As described in the official reference on connecting to external systems, when a dependency changes, React calls the previous cleanup function before running the effect with the new value.
MDN's explanation of performance.now() notes that the specification requires performance.now() to keep advancing while the OS is asleep, but in practice it seems to advance only in browsers on Windows. If you want to keep measuring while a laptop lid is closed, this approach may leave the sleep time out of the elapsed time. MDN also says that Date.now() can sometimes be a better fit for measuring long durations. I did not test this behavior in my environment.
Truncating the display to 1/100 seconds
The elapsed time comes out as a fractional number of milliseconds. First I truncate it to an integer in units of 1/100 second, then format it as a "minutes:seconds.1/100 seconds" string. If the time reaches one hour or more, I add the hours in front.
// Truncate milliseconds to an integer in units of 1/100 second (centiseconds)
export const toCentis = (ms: number) => Math.floor(ms / 10);
// Format an integer in 1/100 seconds as "min:sec.1/100 sec". Prefix hours if it is one hour or more
export function formatCentis(cs: number): string {
const h = Math.floor(cs / 360000);
const m = Math.floor(cs / 6000) % 60;
const s = Math.floor(cs / 100) % 60;
const c = cs % 100;
const pad = (n: number) => String(n).padStart(2, '0');
const text = `${pad(m)}:${pad(s)}.${pad(c)}`;
return h > 0 ? `${h}:${text}` : text;
}
A stopwatch should not show time that has not yet elapsed, so I truncate rather than round up. I passed several millisecond values through toCentis and then formatCentis (the left column is in milliseconds).
--- formatCentis ---
0 00:00.00
9 00:00.00
10 00:00.01
999 00:00.99
59999 00:59.99
60000 01:00.00
3599999 59:59.99
3600000 1:00:00.00
4523456 1:15:23.45
Storing laps as running totals at each press
For laps, I store an array of the running totals in milliseconds at each press (splits in useStopwatch), not the "time since the last press." When the table is rendered, each running total is truncated to 1/100 second, and then the difference from the previous one gives the lap.
import { toCentis } from './time';
export type Lap = { no: number; lap: number; total: number }; // lap and total are in 1/100 seconds
// Derive laps from the running totals (ms) recorded at each press.
// Truncate the totals to 1/100 seconds before subtracting, so the laps add up to the displayed total
export function toLaps(splits: number[]): Lap[] {
const totals = splits.map(toCentis);
return totals.map((total, i) => ({ no: i + 1, total, lap: total - (i === 0 ? 0 : totals[i - 1]) }));
}
// Fastest and slowest lap values. Returns null if there are fewer than two laps or all laps are equal
export function lapRange(laps: Lap[]): { min: number; max: number } | null {
if (laps.length < 2) return null;
const values = laps.map((l) => l.lap);
const min = Math.min(...values);
const max = Math.max(...values);
return min === max ? null : { min, max };
}
If you reverse the order, subtracting in milliseconds first and truncating afterward, the display does not add up. I compared the case where the running totals at each press were 1005, 2004, 3003, and 4002 milliseconds.
押した時点の通算(ms): 1005, 2004, 3003, 4002
通算の表示 : 00:04.00
先に引いてから切り捨て: 00:01.00 00:00.99 00:00.99 00:00.99 合計 00:03.97
切り捨ててから引く : 00:01.00 00:01.00 00:01.00 00:01.00 合計 00:04.00
The running total is displayed as "00:04.00," but with the subtract-first method, each lap after the first becomes 999 milliseconds, which truncates to "00:00.99," and the sum is "00:03.97." The running total is also truncated to the same 1/100-second unit. If you truncate first and then subtract, the sum of the laps always matches the final displayed running total.
I also pressed Lap eight times at about 0.3-second intervals in real time, without controlling the clock. The sum of the displayed laps matched the running total at the last lap.
$ node test/real.mjs
1 | 00:00.35(最速) | 00:00.35
2 | 00:00.37 | 00:00.72
3 | 00:00.37 | 00:01.09
4 | 00:00.37 | 00:01.46
5 | 00:00.38 | 00:01.84
6 | 00:00.38 | 00:02.22
7 | 00:00.40(最遅) | 00:02.62
8 | 00:00.40(最遅) | 00:03.02
表示されたラップの合計(1/100秒): 302 最後のラップの通算(1/100秒): 302
Syncing the current time when a lap is pressed
The call to setNow(t) inside lap is there for a reason. The running total on screen is calculated from now as of the last requestAnimationFrame callback, so it can be a little older than the moment the button was pressed. The running total for the lap, on the other hand, is calculated from performance.now() at the moment of the press.
If now is not synced, the lap's running total becomes newer than the displayed one, and the lap in progress (the running total minus the last lap's total) can become negative. I checked this by stopping the clock and pressing Lap at times between frames (1.208 seconds and 2.206 seconds after the start).
now をそろえる:
押す直前の表示 00:01.20 → 途中のラップの行: 2 | 00:00.00 | 00:01.20
押す直前の表示 00:02.19 → 途中のラップの行: 3 | 00:00.00 | 00:02.20
now をそろえない:
押す直前の表示 00:01.20 → 途中のラップの行: 2 | 00:00.00 | 00:01.20
押す直前の表示 00:02.19 → 途中のラップの行: 3 | -1:-1.-1 | 00:02.19
Without syncing now, right after the second lap press the displayed running total stayed at "00:02.19," while the lap's running total was "00:02.20." Passing the difference of -1 (in 1/100 seconds) to formatCentis broke the in-progress lap row, which displayed as "-1:-1.-1." With syncing, the displayed running total matches the lap at "00:02.20."
Highlighting the fastest and slowest laps
lapRange returns the shortest and longest lap values only when there are two or more laps and the values differ.
--- lapRange ---
1つだけ : null
全部同じ : null
1.20/0.90/1.50: { min: 90, max: 150 }
As explained in WCAG's guidance on the use of color, distinguishing items by color alone does not get the message across to people who have difficulty seeing colors. So in the table, I add a marker reading "(fastest)" or "(slowest)" after the lap time and also change the text color. (In the code, the marker text is the Japanese words for fastest and slowest.) If several laps have the same value, each one gets the same marker.
Putting it on the screen
This is the component that uses the hook and the lap functions. While the watch is running, it shows the Lap and Stop buttons. While it is stopped, it shows the Reset and Resume buttons. Before it has ever started, it shows a Start button and a disabled Reset button. (The button labels in the code are in Japanese.) The top row of the table shows the lap in progress, and the recorded laps are listed from newest to oldest.
import { lapRange, toLaps } from './laps';
import { formatCentis, toCentis } from './time';
import { useStopwatch } from './useStopwatch';
export function Stopwatch() {
const { running, elapsed, splits, start, stop, lap, reset } = useStopwatch();
const total = toCentis(elapsed);
const laps = toLaps(splits);
const range = lapRange(laps);
const current = total - (laps.at(-1)?.total ?? 0); // the lap in progress
const idle = !running && elapsed === 0;
return (
<div>
<p className="time">{formatCentis(total)}</p>
{running ? (
<>
<button onClick={lap}>ラップ</button>
<button onClick={stop}>停止</button>
</>
) : (
<>
<button onClick={reset} disabled={idle}>リセット</button>
<button onClick={start}>{idle ? '開始' : '再開'}</button>
</>
)}
<table>
<thead>
<tr><th>ラップ</th><th>タイム</th><th>通算</th></tr>
</thead>
<tbody>
{!idle && (
<tr className="current">
<td>{laps.length + 1}</td><td>{formatCentis(current)}</td><td>{formatCentis(total)}</td>
</tr>
)}
{[...laps].reverse().map((l) => {
const mark = l.lap === range?.min ? 'fastest' : l.lap === range?.max ? 'slowest' : undefined;
return (
<tr key={l.no} className={mark}>
<td>{l.no}</td>
<td>{formatCentis(l.lap)}{mark === 'fastest' ? '(最速)' : mark === 'slowest' ? '(最遅)' : ''}</td>
<td>{formatCentis(l.total)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
For each row's key, I use the lap number (l.no) rather than the array index. New laps are added to the top of the table, so if the index were the key, every existing row's key would shift on each lap press.
I opened a page with <Stopwatch /> in Chromium, stopped the clock with Playwright, and pressed the buttons at set times. The watch was stopped at 4.000 seconds after the start, and I resumed it after waiting 3 seconds. Each time a button was pressed, I recorded the displayed running total, the buttons, and the table rows. The tags such as <fastest> after each row are the CSS classes on that row.
開いた直後:
00:00.00 [リセット(押せない) 開始]
「開始」を押した(時計で 0.000秒):
00:00.00 [ラップ 停止]
1 | 00:00.00 | 00:00.00 <current>
ラップを押す前(時計で 1.205秒): 00:01.20
「ラップ」を押した(時計で 1.205秒):
00:01.20 [ラップ 停止]
2 | 00:00.00 | 00:01.20 <current>
1 | 00:01.20 | 00:01.20
「ラップ」を押した(時計で 2.204秒):
00:02.20 [ラップ 停止]
3 | 00:00.00 | 00:02.20 <current>
2 | 00:01.00(最速) | 00:02.20 <fastest>
1 | 00:01.20(最遅) | 00:01.20 <slowest>
「ラップ」を押した(時計で 3.703秒):
00:03.70 [ラップ 停止]
4 | 00:00.00 | 00:03.70 <current>
3 | 00:01.50(最遅) | 00:03.70 <slowest>
2 | 00:01.00(最速) | 00:02.20 <fastest>
1 | 00:01.20 | 00:01.20
「停止」を押した(時計で 4.000秒):
00:04.00 [リセット 再開]
4 | 00:00.30 | 00:04.00 <current>
3 | 00:01.50(最遅) | 00:03.70 <slowest>
2 | 00:01.00(最速) | 00:02.20 <fastest>
1 | 00:01.20 | 00:01.20
停止して3秒後: 00:04.00
「再開」を押した(時計で 7.000秒):
00:04.00 [ラップ 停止]
4 | 00:00.30 | 00:04.00 <current>
3 | 00:01.50(最遅) | 00:03.70 <slowest>
2 | 00:01.00(最速) | 00:02.20 <fastest>
1 | 00:01.20 | 00:01.20
「ラップ」を押した(時計で 8.100秒):
00:05.10 [ラップ 停止]
5 | 00:00.00 | 00:05.10 <current>
4 | 00:01.40 | 00:05.10
3 | 00:01.50(最遅) | 00:03.70 <slowest>
2 | 00:01.00(最速) | 00:02.20 <fastest>
1 | 00:01.20 | 00:01.20
「停止」を押した(時計で 8.500秒):
00:05.50 [リセット 再開]
5 | 00:00.40 | 00:05.50 <current>
4 | 00:01.40 | 00:05.10
3 | 00:01.50(最遅) | 00:03.70 <slowest>
2 | 00:01.00(最速) | 00:02.20 <fastest>
1 | 00:01.20 | 00:01.20
「リセット」を押した(時計で 8.500秒):
00:00.00 [リセット(押せない) 開始]
エラーと警告: なし
The laps pressed at 1.205, 2.204, and 3.703 seconds have running totals truncated to 1/100 second, displayed as "00:01.20," "00:02.20," and "00:03.70." The laps are 1.20, 1.00, and 1.50 seconds. During the 3 seconds the watch was stopped, the running total stayed at "00:04.00." After resuming, the lap pressed 1.1 seconds later had a running total of "00:05.10." The time spent stopped was not counted.





