AniUI Academy

Write sleep() with promises

easyAsync & Promises+150 XPPractice

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 continues

Pauses 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 drains

Even sleep(0) yields before resolving.

What it has to do

  • Return a real Promise instance, even for ms of 0.
  • Resolve after at least ms milliseconds, 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

  • setTimeout is clamped to a minimum of around 4ms in most browsers, so very short sleeps may wait slightly longer than requested.
  • Hand resolve directly to setTimeout — wrapping it in an arrow function works, but is noise.
Asked atMetaMicrosoft

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.