Skip to curriculum
Jump to the editor

11.6. Sleep

Easy
Topics

This question is in

11. Timers
10–20 min

Many languages have a sleep(1000) that stops the program for a second. JavaScript cannot stop: the page has one main thread, and blocking it would freeze scrolling, typing and painting. What it can do is hand back a promise that settles a second later, so an async function can await it and pick up where it left off while everything else keeps running. A real helper also needs a way out: when the user leaves the screen, a pending wait should end at once instead of running code later.

Write sleep(ms, options) in sleep.js.

Signature

JAVASCRIPT
function sleep(ms, options) // returns a Promise
  • ms: milliseconds to wait. Missing, 0 or negative means a 0 ms timer.
  • options: optional. options.signal is an AbortSignal; aborting it ends the wait early.
  • Returns a Promise that resolves with undefined after ms ms, or rejects with signal.reason if the signal is aborted first.

Requirements

  1. sleep returns a real Promise, and the code after the call runs at once: nothing is blocked.
  2. The promise resolves ms ms after the call, not earlier, and its value is undefined. It leaves no timer behind.
  3. Even sleep(0), sleep(-5) and sleep() wait for a timer: the promise is not resolved before the timer fires.
  4. Awaiting sleeps one after another adds up: await sleep(100); await sleep(200); ends 300 ms after it starts. Sleeps started together resolve in order of their end time, and ones with the same ms in the order they were called.
  5. Aborting the signal while waiting rejects the promise with signal.reason (by default a DOMException named "AbortError", or the reason passed to abort(reason)), and clears the timer.
  6. A signal that is already aborted rejects straight away, without starting a timer.
  7. Once the promise has resolved, aborting the signal changes nothing and causes no error. sleep also removes the abort listener it added, so a long-lived signal does not collect listeners.
  8. One signal can end many sleeps at once.
  9. sleep(ms), sleep(ms, {}) and sleep(ms, { signal: undefined }) all work.

Examples

JAVASCRIPT
async function blink() {
  console.log("on");
  await sleep(500);
  console.log("off");      // 500 ms later
}
blink();
console.log("not blocked"); // printed right after "on"
JAVASCRIPT
const controller = new AbortController();
sleep(5000, { signal: controller.signal })
  .then(() => console.log("done"))
  .catch((error) => console.log(error.name)); // "AbortError"
controller.abort();                              // ends the wait now
JAVASCRIPT
await sleep(0);   // still waits for a timer, after the current task
const already = AbortSignal.abort();
await sleep(100, { signal: already }); // rejects at once with an AbortError

Environment

  • Plain JavaScript in a browser page; the tests call the global sleep from sleep.js.
  • The tests run on a virtual clock that replaces setTimeout, clearTimeout and Date.now; use setTimeout. No busy loops.
  • AbortController and AbortSignal are the browser's own.

Hints

  1. A promise is resolved by calling the resolve function its executor receives. Who should call it, and when?
  2. If the signal fires after the timer already resolved the promise, what is left to clean up, and what should already have been cleaned up?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…