sleep()
Returns a promise that resolves after time milliseconds.
When signal is passed and becomes aborted before the delay elapses, the promise rejects with signal.reason (same as native fetch / AbortController usage). The timeout is cleared on abort so no resolve happens after cancellation.
Examples:
Basic pause in an async function:
ts
await sleep(250);
console.log('after 250ms');Cancellable delay tied to component unmount or user action:
ts
const ac = new AbortController();
try {
await sleep(5000, ac.signal);
} catch (e) {
// aborted — e is signal.reason
}
ac.abort('user cancelled');