Write sleep() with promises
Sooner or later you need to wait — before a retry, between polling attempts, or to let an animation finish. setTimeout alone does not compose with await, so teams wrap it once and reuse it everywhere.
Implement sleep(ms). It returns a Promise that resolves with undefined after at least ms milliseconds have passed, and it must never reject. sleep(0) still resolves asynchronously — code that runs after the call but before the promise settles must run first. Nothing about the page should be blocked while waiting, so a busy loop is not a solution.
Arguments
msnumber- Milliseconds to wait before the promise resolves.
Returns
Promise<void> — A promise that resolves with undefined after at least ms milliseconds. Never rejects.
Examples
await sleep(100);
// 100ms later: execution continuesPauses without blocking the thread.
let done = false;
sleep(0).then(() => { done = true; });
// done === false here — sleep(0) is still asynchronous
await Promise.resolve();
// done becomes true after the microtask queue drainsEven sleep(0) yields before resolving.
What it has to do
- Return a real
Promiseinstance, even formsof 0. - Resolve after at least
msmilliseconds, never before. - Resolve asynchronously: any code that follows the call synchronously runs first.
- Several sleeps started at once must resolve in order of their durations.
Notes
setTimeoutis clamped to a minimum of around 4ms in most browsers, so very short sleeps may wait slightly longer than requested.- Hand
resolvedirectly tosetTimeout— wrapping it in an arrow function works, but is noise.
Stuck? The javascript course covers everything this challenge needs.
- 1.returns a Promise
- 2.waits at least the requested time
- 3.resolves asynchronously even for 0ms
- 4.shorter sleeps resolve before longer ones
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.