Timers
useDelay runs code once after a wait, useInterval runs it on a repeat, and
onTimer runs it as often as the screen can change.
Once, after a delay
Section titled “Once, after a delay”useDelay(() => { line.hide = true; }, { afterMs: 2000 });Repeatedly
Section titled “Repeatedly”const tick = useInterval(paused === 1 ? undefined : () => { if (left === 0) { tick.stop(); } else { setLeft(left - 1); }}, { everyMs: 1000 });tick.stop() stops it. An undefined body pauses it, as above while paused
is 1.
Delay or interval
Section titled “Delay or interval”useDelay | useInterval | |
|---|---|---|
| Runs | once | until stopped or cleared |
| Timing measured from | when the component appeared | a global clock |
| First run | exactly afterMs later | at the next multiple of everyMs |
“Every second” means on the second, so intervals tick together. For “one
second from now”, use useDelay.
Every frame
Section titled “Every frame”onTimer is a handler prop that fires about fifty times a second until
stopTimer takes it off:
onTimer={(event) => { if (step >= FADE_STEPS) { stopTimer(event.self); } else { setStep(step + 1); }}} />stopTimer takes a ref or event.self, the component the timer fired on. Use
useInterval(fn) for a fade or a spin.
A hidden host is deaf
Section titled “A hidden host is deaf”A timer runs on a component, its host: the component’s root, unless the
third argument of useInterval names another. A timer under a hide does not
run, so when a timer seems dead, look up the tree for a hide.
useInterval(() => { setTicks(ticks + 1); }, { everyMs: 200 }, host);The reference has a page for each: useInterval, useDelay and stopTimer.