QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Sleep

Verified

Promise-based delay with optional AbortSignal cancellation.

  • sleep
  • delay
  • promises

Install

npx shadcn@latest add https://quicksnip.dev/r/sleep.json

Code

/** Resolves after `ms` milliseconds. Pass an AbortSignal to cancel the wait early. */
export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener(
      "abort",
      () => {
        clearTimeout(timer);
        reject(signal.reason);
      },
      { once: true },
    );
  });
}

Usage

await sleep(500);
await sleep(5000, controller.signal); // rejects if aborted