Lesson 6 of 8

Request timeouts

Goal

Put a limit on the wait

01

Explanation

A request with no timeout can wait forever if the network is weak or the server is stuck, leaving the user staring at "Loading…" with no end in sight. It's better for the request to fail after a few seconds with a clear message, so the user knows to try again.

Promise.race returns the outcome of whichever promise settles first, whether it succeeds or fails. So make the request race against a promise that rejects when time is up: if the request finishes first, its result goes through, and if the timer wins, the race fails with the timeout error.

Keep in mind that a timeout ends your waiting, not the request itself. The request keeps running in the background until its response arrives, with nobody waiting for it anymore. Actually stopping it is the subject of the next lesson.

02

Your task

Write the function withTimeout(promise, ms). If the promise settles within ms milliseconds, pass its outcome through unchanged, whether that's a value or an error. Otherwise, reject with new Error('Request timed out').

Checks

5 checks
  1. A fast request passes its value through
  2. A slow request is rejected when time runs out, not after it arrives
  3. The rejection carries an error that mentions the timeout
  4. The request's own error comes through unchanged
  5. The slow request button shows the timeout message
03

Hints

0/3
Track lessons0 of 8 done

Learn to read JSON, wait for the server to respond, and handle loading and failure states. That's what separates a demo from a product people can rely on.

Intermediate level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

Learn to read JSON, wait for the server to respond, and handle loading and failure states. That's what separates a demo from a product people can rely on.

Intermediate level, 8 lessons, 2 hours in total.