React Dojo

Search

Search concepts, exercises and quizzes

practicebasic

Stopwatch with intervals

Build a stopwatch you can start, pause, and reset. Use a ref to store the interval ID — not state — and always clean up in the cleanup function so the timer doesn't stay alive when unmounted.


Objectives

  1. 1.elapsed (ms) state that starts at 0
  2. 2.running (boolean) state that controls the start/pause button
  3. 3.When running, use setInterval every 10ms with functional update: setElapsed(e => e + 10)
  4. 4.Store the interval ID in a useRef — not in state
  5. 5.The useEffect cleanup calls clearInterval with the stored ID
  6. 6.reset button sets elapsed to 0 and pauses
  7. 7.Output format: mm:ss.cc (centiseconds)
your code
Hint

Return a cleanup function from useEffect that calls clearInterval. The useEffect should depend on [running] so it restarts when pausing/resuming.

Related concepts

Was this helpful?
Sign in to give feedback