Command Palette

Search for a command to run...

Hectal
Phase 10: Asynchronous JavaScript
JavaScript · Exercise 4 of 5 PreviousNext
Intermediate

Give any promise a deadline

Write withTimeout(promise, ms). It returns a new promise that settles the same way as promise, unless ms milliseconds pass first: then it rejects with new Error("Timed out after <ms> ms"), for example Timed out after 100 ms.

If promise rejects first, pass its own error along unchanged. Bonus: clear your timer once the result is known.

The demo at the bottom should print Error: Timed out after 100 ms.

What Check tests

  1. A fast promise passes its value through
  2. A slow promise rejects with Timed out after 100 ms
  3. It rejects at the deadline, without waiting for the slow promise
  4. The promise's own error passes through
  5. The demo prints Error: Timed out after 100 ms

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.