Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

fetch, AbortController & Retries — JavaScript interview guide

18 / 23Browser & Practical JSHigh priorityMedium 25 min

fetch, AbortController & Retries

fetch returns a promise for a Response. It only rejects on network failure, so you must check res.ok yourself. AbortController cancels requests.

See it run

Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.

fetch runs in the browser — and AbortController can cancel it

Execution phaseStep 1/8
script.js
▶const controller = new AbortController();
2
3fetch("/api/search?q=re", { signal: controller.signal })
4 .then((res) => res.json())
5 .then((data) => console.log(data))
6 .catch((err) => console.log(err.name));
7
8controller.abort(); // user typed again
Call Stack
last in, first out
Globalrunning
Memory / Scope
Global
controllerAbortController
signal.abortedfalse
Web APIs (browser)
runs outside JS

empty

Event Loop

Waits until the Call Stack is empty. Microtasks always go first.

Microtask Queue
promises · high priority

empty

Callback Queue
setTimeout, events

empty

Console

nothing printed yet

What happens:An AbortController gives us a signal we can pass to fetch, and an abort() button we can press later.

Tip: click the box and use ← → keys to step, space to play.

Explained simply

A safe fetch helper

Check status, parse JSON, and support cancelling.

async function getJSON(url, { signal } = {}) {
  const res = await fetch(url, { signal });
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

const controller = new AbortController();
getJSON("/api/search?q=re", { signal: controller.signal });
controller.abort(); // cancels — the promise rejects with AbortError

Avoid race conditions in search

When the user types fast, an old slow response can arrive after a newer one. Abort the previous request before starting a new one.

Remember this

  • 404 and 500 do NOT reject fetch.
  • Abort old requests on new input or unmount.
  • Use exponential backoff for retries.

Interview questions

Does fetch reject on a 404?

No. fetch rejects only on network errors or abort. A 404 resolves with res.ok === false.

Practice

  1. Write fetchWithRetry(url, retries, delay) with exponential backoff.
  2. Add a timeout to fetch using AbortSignal.timeout.

Keep learning