Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 1

Cancellation, Debouncing and Out-of-Order Responses

Keep a request-happy UI honest: drop stale responses, cancel work with AbortController, cap wait times with timeouts, and fire fewer requests with debouncing.

Contentsand lesson path

What you will learn

  • Cancel or ignore stale requests with AbortController and show loading, empty, error and retry states to the user.

Prerequisites: JavaScript Foundations

01. Why it matters

Search-as-you-type sends a request for almost every keystroke, and the network does not promise fairness: responses can arrive in any order, take any amount of time, or never arrive. Three separate problems follow, and each needs its own tool:

  • a slow response to an old query can arrive last and overwrite the results for the new one — a race;
  • an in-flight request for a query the user has abandoned is wasted work, and its late arrival is the race above — cancellation fixes both;
  • firing a request per keystroke sends too many requests in the first place — debouncing fixes that.

The demos run against a tiny local API that waits a given number of milliseconds before answering, so the timing is visible and repeatable:

JavaScript · slow-api.mjs (the mock used below)
import { createServer } from 'node:http';

createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const label = url.searchParams.get('label') ?? 'anon';
  const ms = Number(url.searchParams.get('ms') ?? 100);
  setTimeout(() => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ label, waitedMs: ms }));
  }, ms);
}).listen(4300, () => console.log("slow API on http://localhost:4300"));

02. Responses arrive in finish order, not send order

JavaScript · outoforder.mjs
const BASE = 'http://localhost:4300/slow';

const first = fetch(`${BASE}?label=rea&ms=400`).then((res) => res.json());
const second = fetch(`${BASE}?label=react&ms=100`).then((res) => res.json());

first.then((data) => console.log('render:', data.label));
second.then((data) => console.log('render:', data.label));
Expected output
render: react
render: rea

The request for rea was sent first, but the one for react — the query the user actually finished typing — answered faster and rendered first. Then the stale response landed and rendered after it. If those lines were DOM updates, the panel would end up showing results for rea while the input box says react.

Nothing is broken in the code above: it faithfully renders every response. The bug is the missing question, is this response still current? — which the rest of the lesson answers three ways. Note that no amount of await fixes this; ordering is a property of the network, not of your syntax.

03. Cancelling with AbortController

JavaScript · abort.mjs
const controller = new AbortController();

fetch("http://localhost:4300/slow?label=rea&ms=500", {
  signal: controller.signal,
})
  .then((res) => res.json())
  .then((data) => console.log("render:", data.label))
  .catch((err) => {
    if (err.name === 'AbortError') console.log('cancelled quietly:', err.name);
    else console.log('real failure:', err.name, err.message);
  });

setTimeout(() => controller.abort(), 100); // the user keeps typing
Expected output
cancelled quietly: AbortError

An AbortController is a switch wired into the request through its signal. Calling abort() rejects the pending fetch with a DOMException named AbortError — so a cancellation flows through your ordinary catch, and you must tell it apart from real failures. A cancellation is not an error: the usual response is to say nothing and let the newer request own the UI.

Two details round out the picture. Once the response body has been fully read (await res.json() has returned), calling abort() changes nothing: the work is done and catch does not run again. However, if headers arrived but the body is still streaming, calling abort() will cause res.json() to reject with an AbortError. And cancelling the sender is not the same as ignoring the result — the next section shows a guard that works even when you cannot cancel.

JavaScript · timeout.mjs
try {
  const res = await fetch("http://localhost:4300/slow?label=rea&ms=500", {
    signal: AbortSignal.timeout(100), // give up after 100 ms
  });
  console.log('render:', (await res.json()).label);
} catch (err) {
  console.log('gave up:', err.name, '-', err.message);
}
Expected output
gave up: TimeoutError - The operation was aborted due to timeout

AbortSignal.timeout(ms) builds a signal that aborts itself after the given time, and a fetch aborted by a timeout rejects with TimeoutError instead of AbortError. A request without a timeout can hang for a minute or more; with one, "server too slow" becomes an ordinary error state your UI can show. Keep the two names straight in the catch: TimeoutError means you gave up, AbortError means your code cancelled it on purpose.

04. Guarding results: only the latest may render

JavaScript · guard.mjs
const BASE = "http://localhost:4300/slow";
let latest = 0; // ticket number of the newest request

async function search(query, ms) {
  const ticket = ++latest;
  const res = await fetch(`${BASE}?label=${query}&ms=${ms}`);
  const data = await res.json();
  if (ticket !== latest) {
    console.log(`dropped stale response for "${data.label}"`);
    return;
  }
  console.log(`rendered "${data.label}"`);
}

search('rea', 400);   // slow: the user's first idea
search('react', 100); // fast: the finished word
Expected output
rendered "react"
dropped stale response for "rea"

Each call takes a ticket; after the response arrives, a ticket that is no longer the newest means the user has moved on, and the result is dropped. This pattern costs one variable, needs no cooperation from the API, and works even for work that cannot be aborted, such as expensive rendering. In a real client, cancellation and the guard do slightly different jobs: aborting frees the network work early, while the ticket is the last line of defence that keeps stale data off the screen even if a response slips through.

05. Debouncing: one request per pause

JavaScript · debounce.mjs
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

const search = debounce((query) => console.log("searching for:", query), 200);

setTimeout(() => search('r'), 0);
setTimeout(() => search('re'), 100);
setTimeout(() => search('rea'), 200);
setTimeout(() => search('reac'), 500);
setTimeout(() => console.log('(done)'), 1200);
Expected output
searching for: rea
searching for: reac
(done)

A debounced function resets its timer on every call and only runs after the calls stop for the given interval. Four keystrokes here produced two searches: the first three keys arrived within 200 ms of each other, so each one cancelled the previous timer, and only the pause after rea (and after reac) let a search through. Fewer requests, cheaper for the API, calmer for the UI.

Debounce is not the only timing pattern: throttling lets a function run at most once per interval while events keep coming, which suits scroll and resize handlers where you want continuous feedback. Debounce suits text input, where the last value is the only one you care about. And remember from lesson 1 that all of this is still timers and one thread — debounce simply chooses which keystroke earns a task.

06. What the user must see

Cancellation and guards protect the data; the interface still has to tell the truth at every moment. A search panel needs four distinguishable states:

  • loading — a request is in flight; the user should wait, not retype;
  • empty — the request succeeded and genuinely found nothing; rephrasing may help;
  • error — the request failed (HTTP error or network failure), with a way to try again;
  • results — data to display.

Collapsing them is how blank screens happen: a spinner that keeps spinning for an empty result, or "no results" shown during a failure, each teaches the user to distrust the page. The lab builds a small state machine that switches between exactly these four, with a retry button that re-runs the same search function.

07. Check your understanding

Practice check · 3 questions

Races and timing in practice

Predict behaviour from the patterns, not from hope.

Q1. A search is debounced by 300 ms. Keys arrive at 0 ms, 150 ms and 600 ms. When does the search function run?
Q2. You call `controller.abort()` after `await res.json()` has already completed. What happens?
Q3. A scroll handler should run at most once every 100 ms *while* the user keeps scrolling. Which pattern fits?
Practice only: not graded, not saved, not evidence.

08. Apply it

These three tools combine in the lab. Before it, try them separately against the mock API:

  1. Run the out-of-order demo, then add the ticket guard and watch the stale render disappear. Add AbortController as well and time how much earlier the network work stops.
  2. Give debounce a leading-edge option: a flag so the first call runs immediately and later calls within the interval are dropped. Compare with AbortSignal.timeout for capping waits.
  3. Break the abort demo on purpose: remove the err.name === "AbortError" check and observe how a normal user action turns into a scary red error. That is the bug the check prevents.

09. Review prompt

Without looking back: why can responses arrive in a different order than requests, and what question must every render answer before displaying a response? What does controller.abort() do to a pending fetch and to a settled one, which two error names matter in the catch, and what does AbortSignal.timeout add? Finally, contrast debounce with throttle, and name the four states a search panel must distinguish.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check