Sleep with a Promise
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a Promise that resolves (with `undefined`) after `ms` milliseconds, so callers can write `await sleep(500)`. It must always return a Promise, even for `sleep(0)`. Tests run on a fake clock: `setTimeout`, `clearTimeout` and `Date.now` are simulated, so waits are instant and exact.
What this exercise teaches
The Promise constructor hands you resolve; giving it to setTimeout resolves the Promise when the timer fires. The function always returns the Promise, so sleep(0) still waits for the next timer turn.
A hint if you get stuck
Wrap `setTimeout` in `new Promise((resolve) => ...)` and pass `resolve` as the timer callback.
This exercise is part of Pro
Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.
You create a free account first, so Pro is attached to it.
Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.