QuestionsJavaScript

Promise-based sleep and a timeout wrapper

Promises / TimersMediumJavaScript

Implement sleep(ms) as a promise, then a withTimeout(promise, ms) that rejects if the work doesn't settle in time.

What it tests

Promisifying setTimeout, composing with Promise.race for deadlines, and cleaning up the timer to avoid leaks.

Approach & answer

sleep is the canonical promisify example: wrap setTimeout so `await sleep(ms)` pauses an async function without blocking the thread — `return new Promise(resolve => setTimeout(resolve, ms))`. It reads linearly inside async code and is the building block for delays between retries, staggering requests, or animations. The timeout wrapper is a Promise.race composition: race the real work against a promise that REJECTS after ms — whichever settles first wins, so if the work is slow the timeout rejection propagates and callers can surface 'request timed out'. Two important refinements interviewers look for: (1) capture the timer id and clearTimeout it once the race settles, so a resolved-fast promise doesn't leave a dangling timer (and, in Node, doesn't keep the process alive) — do this in a .finally or by clearing in both race branches. (2) Note the losing promise is NOT cancelled — JS promises have no built-in cancellation, so the slow work keeps running in the background; for real cancellation (e.g. fetch) you pair this with an AbortController and abort in the timeout branch. This race-against-a-timer is exactly how you add deadlines to fetches, and how you avoid an async operation hanging forever.

Use this technique when

Adding deadlines to fetches/RPCs, delays between retries or polls, and staggering async work — pairing with AbortController for true cancellation.

Complexity

O(1); one extra timer per wrapped call.

References

js