Live coding ยท 25 minutes
Stopwatch with laps
Build a stopwatch in React in 25 minutes. It shows the elapsed time as minutes, seconds and hundredths of a second. It has Start, Pause, Reset and Lap buttons and a list of lap times. The time must stay correct when the tab is in the background or the computer is busy, so you cannot count timer ticks. Explain your decisions while you code, as in a live round.
Requirements
- Start begins counting; Pause stops and keeps the time; Start then continues from that time
- Reset stops the stopwatch, sets the time to zero and clears the laps
- Lap adds the current time to a list while the stopwatch runs
- The elapsed time is computed from timestamps (performance.now or Date.now), not by adding a fixed amount on each tick
- The display has the form mm:ss.hh with leading zeros
- The timer is cleared on pause, on reset and on unmount
- A button is disabled when it has no meaning, for example Lap while the stopwatch is stopped
What reviewers look for
- The key idea is said early: keep the start timestamp and the time already counted, and compute the elapsed time from them
- The interval or requestAnimationFrame only asks for a new render; it is not the source of the time
- Refs for the timer id and the timestamps, and state for what the screen shows
- Cleanup on unmount, and no second timer after a double click on Start
- A pure format function, checked by hand with a few values
- You know that browsers slow down timers in background tabs, and you can say why your design is still correct
Check before you hand it in
- Start, Pause, Start again and Reset each do the right thing, and a double click on Start does not make the time run faster
- Lap adds the current time to the list while the stopwatch runs, and Reset clears the list
- I ran it next to a phone stopwatch with the tab in the background for a minute, and the two times still matched
- The time shows as mm:ss.hh with leading zeros, for example 01:05.07
- The timer is cleared on pause, on reset and when the component unmounts
- I explained each decision aloud, including why counting ticks gives a wrong time
- Start, pause, reset and laps worked within 25 minutes
If there is time
- Show for each lap the time since the lap before it, next to the total
- Keep the stopwatch running across a reload by saving the start time; this needs Date.now, because performance.now starts again with each page load
- Keyboard shortcuts: Space for start and pause, L for lap
- Move the logic into a useStopwatch hook