Sleep / delay with a Promise
Pause an async function for a number of milliseconds, with optional cancellation through AbortSignal.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
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
await sleep(500); // resumes after about half a secondHow 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.
Related snippets
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.
- JavaScript Tested
Retry an async operation with exponential backoff
Retry a failing promise-returning function with growing, jittered delays and a retry predicate.
- Python Tested
Retry decorator with exponential backoff
Re-run a flaky function a limited number of times with growing delays, only for chosen exception types.
- JavaScript Tested
Fetch every page of a paginated API with an async generator
Iterate cursor-paginated API results with for await, loading pages lazily and stopping early when needed.

