JavaScript Snippet

Sleep with a Promise

Difficulty: Easy

Pausing async code is a one-line problem until you need cancellation, a typed signal, or to reuse the helper across files. This snippet starts with the canonical `setTimeout` Promise wrapper, then adds `AbortSignal` support so callers can cancel waits cleanly. Drop it into any toolkit and stop reaching for `setTimeout` callbacks in async functions.

Code Snippets
/

Sleep with a Promise

Sleep with a Promise

Pausing async code is a one-line problem until you need cancellation, a typed signal, or to reuse the helper across files. This snippet starts with the canonical `setTimeout` Promise wrapper, then adds `AbortSignal` support so callers can cancel waits cleanly. Drop it into any toolkit and stop reaching for `setTimeout` callbacks in async functions.

JavaScript
Easy
2 snippets
async-programming
promises
utility
code-template

238 views

5

The canonical sleep wraps setTimeout in a Promise so it composes inside async functions with await. The resolver is the timeout callback, so the promise settles exactly once after ms milliseconds. Use it for retry backoffs, demo pauses, or rate-limited loops where you do not need to cancel the wait. The function is O(1) time and uses one timer slot per pending sleep, so do not spawn thousands of them in a tight loop without cleaning up.