Skip to content

useDelay

useDelay runs a body once, afterMs milliseconds after the component appears, then stops.

useDelay(body: () => void, options: { afterMs: Int }): Timer
src/boost.ts2
const Notice = (): Component => {
const line = useRef();
useDelay(() => { line.hide = true; }, { afterMs: 2000 });
return (
<text ref={line} x={0} y="bottom" w="fill" h={16} font={Fonts.SMALL}
text="Overload potion applied." align="center" valign="middle"
shadow color={Colors.GREEN} />
);
};
  • body: A function taking no arguments. Runs once.
  • options.afterMs: A number of milliseconds to wait.

A Timer with a stop() method, for cancelling before it elapses.

  • Refused in a component that reads state (TS2E218). Move the delay into a child that does not read the changing value, or use useInterval and stop it yourself.
  • It uses the component’s one timer, like useInterval and onTimer.
  • A delay under a hide does not fire until the component is shown.
  • Precision is about 20 milliseconds.
refused/use-delay.ts2
const Refused = (): Component => {
const [n, setN] = useState(0);
const line = useRef();
useDelay(() => { line.hide = true; }, { afterMs: 2000 }); // this component redraws
src/boost.ts2
useDelay(() => { line.hide = true; }, { afterMs: 2000 });

The countdown beside it reads state, so the delay lives in Notice:

src/boost.ts2
<layer x={0} y={0} w="fill" h={40}>
<SunkenBox>
<layer x={2} y={2} w={{ fill: 4 }} h={{ fill: 4 }}>
<BoostTimer />
</layer>
</SunkenBox>
</layer>
<Notice />

The component reads state. Split the delay into a child component that does not read that value, as Notice is.

Check the component is visible. A hidden component’s timers do not run, and resume when it comes back.