liveBook · Manning

Timer

As explained in React Quickly, Second Edition

A timer is a runtime mechanism that schedules or repeats execution after a time interval.

A timer schedules repeated work at a time interval. In a React component, an effect can start an interval, update state on each tick, and return cleanup that stops it. section 6.1.2 section 6.1.5

A reliable component timer follows these patterns:

  • Start the interval inside an effect and update the countdown with a state updater. section 6.1.2
  • Return clearInterval cleanup so unmounting or changing timer state does not leave the interval running. section 6.1.5
  • Use an effect dependency such as isRunning when the interval should start and stop without unmounting the component. section 6.1.5
  • Treat setInterval as approximate; use performance.now() when the countdown requires greater precision. section 12.2.1

A stopwatch component

useEffect(() => {\n const interval = setInterval(\n () => setSeconds((seconds) => seconds + 1),\n 1000\n );\n return () => clearInterval(interval);\n}, []);

How React Quickly, Second Edition covers it

How deep it goes
Explains interval setup, state updates, dependency-driven restarts, cleanup, and timing limits without pursuing precision implementation.
Examples
Demonstrates a ticking stopwatch, a pausable countdown, and a componentized timer project.
What it assumes
Uses React state and effects while demonstrating their combination for timer behavior.
What you can do after
Build it from scratch with useEffect, useState, setInterval, and clearInterval, then improve precision with performance.now().
How it connects
Connects timers to React effects, state, component lifecycle, cleanup functions, and componentization.

Also explained in

Compare how 4 books explain timer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.