Fetch JSON with Timeout + Abort
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> — 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.
// 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 AbortErrorPublic 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.
- PracHub: Waymo senior frontend engineer interview experience, May 2026
One self-reported senior loop describes an onsite autocomplete with debouncing that queries a backend. Fetching with a timeout and abort is a supporting drill for cancelling stale requests, not the reported exercise.
Reported in a public Waymo interview account. Waymo frontend interview questions
Solution
Overview
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.
Approach: AbortController + timeout guard
Steps:
1) Extract timeoutMs, signal, and fetchFn from options.
2) Create an AbortController and forward external aborts.
3) If timeoutMs is set, abort with a Timeout AbortError.
4) Call fetch with the combined signal.
5) Throw on non-OK status.
6) Parse and return JSON.
7) Always cleanup listeners and timers.
Complexity: O(1) extra work beyond the network request.
function toAbortError(reason, message = 'Aborted') {
if (reason && reason.name === 'AbortError') return reason;
const err = new Error(reason && reason.message ? reason.message : message);
try { err.name = 'AbortError'; } catch { try { Object.defineProperty(err, 'name', { value: 'AbortError' }); } catch {} }
return err;
}
export default async function fetchJson(url, options = {}) {
const { timeoutMs, signal, fetchFn, ...init } = options;
const fetcher = fetchFn || (typeof fetch === 'function' ? fetch : null);
if (!fetcher) throw new Error('fetchFn is required');
const controller = new AbortController();
let timeoutId;
const onAbort = () => {
controller.abort(toAbortError(signal && signal.reason));
};
if (signal) {
if (signal.aborted) {
controller.abort(toAbortError(signal.reason));
} else {
signal.addEventListener('abort', onAbort, { once: true });
}
}
if (typeof timeoutMs === 'number' && timeoutMs >= 0) {
timeoutId = setTimeout(() => {
controller.abort(toAbortError(null, 'Timeout'));
}, timeoutMs);
}
try {
if (controller.signal.aborted) {
throw toAbortError(controller.signal.reason);
}
const res = await fetcher(url, { ...init, signal: controller.signal });
if (!res || !res.ok) {
const status = res && typeof res.status === 'number' ? res.status : 0;
throw new Error(`HTTP ${status}`);
}
return await res.json();
} finally {
if (timeoutId) clearTimeout(timeoutId);
if (signal) signal.removeEventListener('abort', onAbort);
}
}
function toAbortError(reason: any, message: string = 'Aborted'): Error {
if (reason && reason.name === 'AbortError') return reason;
const err = new Error(reason && reason.message ? reason.message : message);
try { (err as any).name = 'AbortError'; } catch { try { Object.defineProperty(err as any, 'name', { value: 'AbortError' }); } catch {} }
return err;
}
type FetchJsonOptions = {
timeoutMs?: number;
signal?: AbortSignal;
fetchFn?: (input: string, init?: any) => Promise<{ ok: boolean; status: number; json: () => Promise<any> }>;
[key: string]: any;
};
export default async function fetchJson<T = any>(
url: string,
options: FetchJsonOptions = {}
): Promise<T> {
const { timeoutMs, signal, fetchFn, ...init } = options;
const fetcher = fetchFn || (typeof fetch === 'function' ? fetch : null);
if (!fetcher) throw new Error('fetchFn is required');
const controller = new AbortController();
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const onAbort = () => {
controller.abort(toAbortError(signal && (signal as any).reason));
};
if (signal) {
if (signal.aborted) {
controller.abort(toAbortError((signal as any).reason));
} else {
signal.addEventListener('abort', onAbort, { once: true });
}
}
if (typeof timeoutMs === 'number' && timeoutMs >= 0) {
timeoutId = setTimeout(() => {
controller.abort(toAbortError(null, 'Timeout'));
}, timeoutMs);
}
try {
if (controller.signal.aborted) {
throw toAbortError((controller.signal as any).reason);
}
const res = await fetcher(url, { ...init, signal: controller.signal });
if (!res || !res.ok) {
const status = res && typeof res.status === 'number' ? res.status : 0;
throw new Error(`HTTP ${status}`);
}
return await res.json();
} finally {
if (timeoutId) clearTimeout(timeoutId);
if (signal) signal.removeEventListener('abort', onAbort);
}
}
Notes & Pitfalls
Using Promise.race without AbortController does not cancel the fetch. Forgetting to clear timeouts or abort listeners can leak resources. Not checking response.ok can silently treat HTTP 404/500 as success.
signal already aborted: reject immediately. timeoutMs = 0 should timeout immediately. fetchFn not provided and fetch missing: throw a helpful error.
AbortController for cancellation. Timeout guard with setTimeout. Defensive error handling for non-OK responses.
Common mistakes on this challenge
fetchJson timeout/abort bridging is incorrect
This helper should combine timeout controller with external signal and HTTP status checks. Create internal AbortControllerand bridge external abort signal to it.Set timeout that aborts with timeout-specific abort reason when configured. Throw on non-OK responses and return parsed JSON for successful responses.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.