Skip to content
GreenSnippets

Sleep / delay with a Promise

Pause an async function for a number of milliseconds, with optional cancellation through AbortSignal.

JavaScript
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const timer = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);
    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }
    signal?.addEventListener("abort", onAbort, { once: true });
  });
}

Example / expected output

Output
await sleep(500); // resumes after about half a second

How it works

A promise-based timer makes retry loops and demos readable. Passing an AbortSignal lets the caller cancel the wait, and the timer is cleared so nothing keeps the process alive.