useTimeout starts a one‑shot timer and returns the completion flag.
Supports two call forms:
- duration only (in milliseconds);
- callback + duration.
The result can be used as a tuple ([isDone]) or as an object ({ isDone }).
// Variant 1: duration only
function useTimeout(ms: number): UseTimeoutReturn;
// Variant 2: callback + duration
function useTimeout(callback: UseTimeoutCallback, ms: number): UseTimeoutReturn;-
Parameters
ms— timeout duration in milliseconds.callback(optional) — a function invoked after the timeout completes. Receives the actual elapsed time in milliseconds.
-
Returns
- A hybrid structure accessible as:
- Tuple:
[isDone] - Object:
{ isDone }
- Tuple:
- A hybrid structure accessible as:
- On first use, a timer is created with the specified duration.
- When the timer finishes:
- if the
isDonevalue is used by the component, it flips totrue; - if a
callbackwas provided, it is called with the actual elapsed time.
- if the
- If the component unmounts before completion, the timeout is cleared.
- When
mschanges, the existing timer is restarted with the new duration.
import { useTimeout } from '@webeach/react-hooks/useTimeout';
function Loader() {
const { isDone } = useTimeout(2000);
return isDone ? <span>Done!</span> : <span>Loading…</span>;
}import { useTimeout } from '@webeach/react-hooks/useTimeout';
function Example() {
useTimeout((elapsed) => {
console.log(`Timer finished after ${elapsed} ms`);
}, 1000);
return <p>Waiting 1 second…</p>;
}- Show a loading indicator for a fixed time.
- Trigger an action after a delay.
- Obtain the actual elapsed time of a timer (e.g., for logging/metrics).
- You need periodic execution — prefer
useLoop. - You must update state immediately upon unmount/cancel — use a controlled effect or
AbortControllerlogic instead. - You need to manage multiple timers — consider a custom timer manager.
- Relying on
isDonewithout accounting for its lazy update: the flag updates only if it is actually read/used by the component. - Expecting the
callbackto fire at exactlyms— real timing depends on browser load and the event loop; use the providedelapsedvalue.
Exported types
-
UseTimeoutCallback- Callback invoked after the timeout completes:
(actualTime: number) => void. actualTime— the actual time (ms) elapsed since start.
- Callback invoked after the timeout completes:
-
UseTimeoutReturn- Hybrid: tuple
[isDone]and object{ isDone }.
- Hybrid: tuple
-
UseTimeoutReturnObject- Object form:
{ isDone: boolean }.
- Object form:
-
UseTimeoutReturnTuple- Tuple form:
[isDone: boolean].
- Tuple form: