Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 132 ยท Projects

Project: Stopwatch and Countdown Timer

Build a stopwatch with laps and a countdown timer in React. Learn why counting ticks drifts, how to measure real elapsed time with useRef, and how to clean up intervals.

Timers look easy: call setInterval, add one to a number, done. They are a great project because the obvious solution is subtly wrong, and fixing it teaches you three things at once: how to keep a non-visual value in a ref, how to clean up after an effect, and why state should describe what is true rather than what happened.

We will build a stopwatch in three stages and finish with a countdown timer that reuses the same ideas.

The plan

A stopwatch has a running flag, a total of elapsed milliseconds, and a list of lap times. The screen shows the time as mm:ss.cc (minutes, seconds, hundredths) and Start/Stop, Lap and Reset buttons. A small helper formats milliseconds, and we reuse it in every stage:

JavaScript
function format(ms) {
  const total = Math.floor(ms / 10);
  const cs = String(total % 100).padStart(2, '0');
  const s = String(Math.floor(total / 100) % 60).padStart(2, '0');
  const m = String(Math.floor(total / 6000)).padStart(2, '0');
  return `${m}:${s}.${cs}`;
}

Stage 1: the naive version

The first idea is to add ten milliseconds every ten milliseconds. Run it and compare with the "Real" line beside it, which measures the true time with the clock.

Stage 1: counting ticks (drifts)

Browsers promise that a timer fires no earlier than requested, never exactly on time. Each late tick still adds only ten, so the error accumulates.

Stage 2: measure instead of count

The fix: the timer is only a reminder to look at the clock. We remember when we started (in a ref, because changing it must not re-render) and compute elapsed time from timestamps. To support pause and resume we store the time already accumulated.

Stage 2: timestamp based stopwatch

Three details deserve a look:

  1. The interval period (30 ms) only controls how often the screen refreshes; the value is always computed from performance.now(), so it cannot drift.
  2. The effect's cleanup runs when running flips to false, which is exactly when we bank the elapsed time into baseline. This pairs setup and teardown as described in effect cleanup.
  3. All the logic sits in a custom hook, so the component only draws.

Stage 3: laps

A lap records the current elapsed time. We show each lap's own duration (the difference from the previous lap) plus the total. Laps are an array in state, updated immutably (objects and arrays in state). The lap durations are derived during render, never stored.

Stage 3: laps

Using the index as a key is fine here: laps are only ever appended or cleared, never reordered or removed in the middle (lists and keys).

A countdown timer

A countdown is the same idea turned around: remember the deadline, and compute deadline - now. When it reaches zero, stop and announce it.

Countdown timer

Note role="status": screen readers announce the "Time is up!" text when it appears (accessibility).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does adding 10 to the state on every 10 ms interval tick drift from real time?

    A timer only guarantees a minimum delay. Counting ticks accumulates every delay, while reading the clock each time always gives the true elapsed time.
  2. 2. Why is the baseline (time banked before the current run) stored in a ref?

    Refs hold values that persist between renders without triggering one. The displayed value is the state elapsed; the baseline is bookkeeping.
  3. 3. What must the effect return to avoid several intervals running at once?

    The cleanup function runs before the effect re-runs and on unmount. Without it every Start press would leave another interval ticking.
  4. 4. Where should lap durations (the difference between laps) be computed?

    They can be derived from the totals, so storing them too would create two sources of truth that could disagree.

Summary

  • Counting timer ticks drifts; measure real time from performance.now() or Date.now() and let the interval only trigger redraws.
  • Keep bookkeeping values (start time, accumulated time) in refs, and displayed values in state.
  • Always clear intervals in the effect cleanup; pairing setup and teardown makes pause and resume work.
  • A countdown is a stopwatch turned around: store a deadline and show what is left.
  • Derive laps and formatted strings during render.

Next: Project: Calculator