Sleep / Delay Promise
Arguments
ms: number —The delay in milliseconds.
Returns
Promise<void> — Solution idea
This utility wraps setTimeout in a Promise so you can pause async control flow without blocking. It’s a common primitive for polling, retry logic, exponential backoff, and UI timing. The function should integrate cleanly with async/await, return a Promise every time, and behave predictably for zero or negative delays.
// Usage with async/await
await sleep(50);
console.log('done');
// Usage with then
sleep(20).then(() => console.log('ready'));Solution
Overview
This utility wraps setTimeout in a Promise so you can pause async control flow without blocking. It’s a common primitive for polling, retry logic, exponential backoff, and UI timing. The function should integrate cleanly with async/await, return a Promise every time, and behave predictably for zero or negative delays.
Approach: Promise + setTimeout
Return new Promise(resolve => setTimeout(resolve, ms)). Ensure you return the Promise so callers can await it or chain then. If ms is negative or NaN, setTimeout resolves immediately, which is acceptable for this helper. Keep the function tiny and deterministic; it should never block the main thread.
export default function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export default function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
Notes & Pitfalls
Don't forget to return the Promise (otherwise callers cannot await it). setTimeoutreturns a timer id, not a Promise.Negative or NaN delays are treated as 0 by most environments.
ms = 0resolves on the next tick.Very large delays may be clamped by the environment.
Promise construction around callback-based APIs. Basic async timing utilities.
Common mistakes on this challenge
sleep must return a Promise
The function contract should always be Promise-based. Return new Promise((resolve) => { ... })directly fromsleep.Resolve inside setTimeout, do not return from inside the callback only.Re-run and verify the "returns a promise" test passes before timing tests.
Delay timing is too short or inconsistent
The Promise resolves before the expected minimum delay. Use setTimeout(resolve, ms)with the samemsinput, no unit conversion.Avoid immediate resolve paths that bypass the timer. Measure elapsed time around await sleep(ms)to confirm it is at leastms.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.