← Over the wire · all materialsExercise 5 · 6 min · case 1 in class
Act 5 · AbortController

Search without races

Search as you type, on the server: GET /api/stalls?q=tac. Type quickly and the box says one thing while the list shows another, because the response to "t" arrives after the response to "tac". The Race lab draws it.

The pattern. const controller = new AbortController(), pass { signal: controller.signal } to fetch, call controller.abort() when the request is obsolete. The aborted fetch rejects with an error whose name is "AbortError": catch it and ignore it. getJSON(url, options) passes options on to fetch.

1

Abort the obsolete request

Type "tac" quickly: the box says tac, the list shows everything with a t in it.

Keep the current request's AbortController outside the listener. On every input: abort the previous one, make a new one, pass its signal. Ignore AbortError in a catch; let real errors through. Type quickly in the preview, then look at the Network tab.

Homework · bonus

2 · bonus

Debounce

Aborting fixes the display, but every keystroke still costs the server a search. Wait until typing pauses for 250 ms, then search: clearTimeout + setTimeout on every input. Keep the abort: a pause in the middle of a word can still start a slow request.