useDelay
Executes a callback after a configurable delay. Supports both automatic execution on mount and manual trigger mode.
Signature
// Automatic mode
function useDelay(
callback: () => void,
options?: { delay?: number; manual?: false }
): () => void;
// Manual mode
function useDelay(
callback: () => void,
options: { delay?: number; manual: true }
): () => () => void;
Options
| Property | Type | Default | Description |
|---|---|---|---|
delay | number | 250 | Milliseconds before the callback fires |
manual | boolean | false | When true, the hook returns a trigger function instead of auto-executing |
Return value
| Mode | Return | Description |
|---|---|---|
manual: false | () => void | No-op (auto-executes on mount) |
manual: true | () => () => void | Call it to schedule the callback. It returns a function that cancels that run |
- The callback always runs with its latest version, so inline functions are fine.
- In automatic mode, the timer restarts when
delaychanges. - Pending timers, in both modes, are cleared when the component unmounts.
const run = useDelay(save, { delay: 1000, manual: true });
const cancel = run(); // schedules save() in 1 s
cancel(); // cancels that run
Live example
Loading playground...