Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C4 · Lekcja 10
ZadanieBuild the debounced + aborted search. <input id='q' value='anna' /> + <ul id='out'></ul>. On 'input', debounce 200ms then fetch '/api/search?q=' + value, abort previous, parse JSON, render each result as <li>. To make the test exercise the flow, also call the same handler once on load.

Zwieńczenie modułu: pole wyszukiwania z odrzuceniem i przerwaniem

250 XP14 min
Teoria

Putting C4 together

The most-built feature in any modern frontend: a search box that fires off a fetch as you type and shows results. Three things go wrong if you do it naively:

  1. Spam — typing "anna" fires four fetches; the network thrashes.
  2. Stale results — earlier responses arrive after later ones and overwrite the right answer.
  3. Errors don't help — user typed "an" but sees error for "a" because they raced.

The fix

Three patterns from C4 stacked together:

  1. Debounce — wait until the user stops typing (200ms) before fetching.
  2. AbortController — cancel any in-flight request when a new one starts.
  3. r.ok check — surface real HTTP errors, ignore AbortErrors.
let lastController = null;
let timer = null;

input.addEventListener("input", () => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    lastController?.abort();
    lastController = new AbortController();
    try {
      const r = await fetch(`/api/search?q=${encodeURIComponent(input.value)}`, {
        signal: lastController.signal,
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const data = await r.json();
      renderResults(data.results);
    } catch (err) {
      if (err.name === "AbortError") return;
      console.error(err);
    }
  }, 200);
});

Why this pattern is everywhere

Autocomplete in Google, GitHub repo search, npm package search, every admin-panel filter. Same shape. Once you've written it for one project, you'll recognize it in every codebase.

The capstone

Build that exact pattern. The fetch mock simulates an autocomplete API — typing "a", "ann", or "anna" returns different result sets. Your code should:

  • Debounce the input event to 200ms.
  • Abort the previous fetch on every new typed character.
  • Render the JSON.results array as <li> items inside <ul id="out">.
🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.