Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.2 — fetch
JavaScript · Example 3 of 3

Cancel with AbortController, time out with AbortSignal.timeout

abort() with no argument rejects with an AbortError; AbortSignal.timeout() rejects with a TimeoutError, so your code can tell "the user cancelled" from "the server was too slow". The messages shown are Chrome's.

fetch(url, options) sends an HTTP request and returns a promise for a Response; it only rejects on network failure, so you must check response.ok yourself, read the body once with json() or text(), and use an AbortController to cancel or time out.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write async function getName() that fetches data:application/json,{"name":"Meera"}, checks ok, and returns the name. Log the result.

02

Write a fetchWithTimeout(url, ms) helper that rejects with a TimeoutError when the request takes longer than ms.

Explain it without notes

01

Why do you have to check response.ok? When does a fetch promise reject?

02

Why are there two awaits in a typical fetch call?

03

How do you send JSON with fetch, and what goes wrong if you skip JSON.stringify?

04

How do you add a timeout and cancellation to fetch, and how do you tell them apart?

Cancel with AbortController, time out with AbortSignal.timeout

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

real fetch, aborted -> AbortError: signal is aborted without reason
100ms with 400ms timeout -> done after 100ms
900ms with 300ms timeout -> TimeoutError: signal timed out