Usage
Timer is a stopwatch and countdown that can be started, paused, resumed, reset and restarted.
It does not render playback buttons: add them with Timer.Control or control
the timer with useTimer. Set autoStart to start the timer on mount:
Countdown and stopwatch
By default, Timer counts up from startMs. Set countdown prop to count down
from startMs to targetMs instead. In both modes the timer stops at targetMs and calls onComplete:
Changing startMs or countdown stops the timer and resets it to the new startMs.
Format
Set format prop to change the readout, 'HH:mm:ss' by default:
Literal text is not escaped: token letters are replaced with time values even inside words. All tokens except days are capped to their natural range, include a larger token for durations that exceed the largest unit in the format:
To display milliseconds, lower the interval prop so the readout updates more often than once per second:
Custom layout
Pass Timer.Segment, Timer.Separator and Timer.Control as children to replace
the default readout. Timer.Control is a button that calls the controller action
set with the action prop:
useTimer hook
Timer supports the controller pattern with the useTimer hook.
It accepts the same options as Timer props and returns the timer state and actions:
Controlling the timer
Pass the controller created with useTimer to the controller prop.
Timer options set on Timer are then ignored, pass them to useTimer instead:
running: false, paused: false
Progress
When targetMs is set, getProgress() returns a value from 0 to 1.
Use it with Progress or RingProgress:
Timer.parse
Timer.parse (also available as useTimer.parse) converts a duration object, Date or ISO date
string to milliseconds:
With a Date or a date string, the result depends on the current time. Calculate it once,
for example, in a useState initializer: a new startMs value on every render resets the timer:
Timer vs use-countdown
use-countdown is a display-only countdown hook. Use Timer or useTimer
when the timer must count up or be paused, resumed and restarted.
Accessibility
Set aria-label on icon-only timer controls. If ticks need to be announced, use aria-live="polite"
with an interval of at least one second: