Fetch JSON with Timeout + Abort

intermediate
By FrontendAtlas Editorial · Updated Oct 15, 2026
Implement fetchJson(url, options) that fetches JSON with built-in timeout and abort support. It should abort on timeout, respect an external AbortSignal, and throw on non-2xx HTTP responses. This mirrors real-world client utilities for APIs. Concepts: fetch, AbortController, timeouts, error handling.

Arguments

  • url: string — The request URL.
  • options: { timeoutMs?: number, signal?: AbortSignal, fetchFn?: Function, ...init } — Optional timeout, AbortSignal, and a fetch function override for testing. Any extra fields are passed to fetch.

Returns

Promise<any> — Resolves with parsed JSON or rejects on timeout, abort, or non-OK response.

Solution idea

Create a new AbortController per call. If an external signal aborts, forward that to the controller. If a timeout is set, abort after the deadline. Call fetch, throw on non-OK status, and return response.json(). Always clear timers and listeners.

Examples
// Basic usage
const data = await fetchJson('/api/user/42', { timeoutMs: 2000 });

// With external cancellation
const ac = new AbortController();
const p = fetchJson('/api/search?q=js', { signal: ac.signal });
ac.abort();
await p; // rejects with AbortError

Public interview reports

These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.

Reported in a public Waymo interview account. Waymo frontend interview questions