← Tous les articles

Search-as-you-type in JavaScript: debounce it, cancel stale requests

Firing a request on every keystroke means a dozen calls per word and results arriving out of order. Debounce, cancel outdated requests, render safely and accessibly: the version we actually ship.

Search-as-you-type in JavaScript: debounce it, cancel stale requests

Key points

  • Debouncing waits for the user to pause before sending the request.
  • Each new search aborts the previous one with AbortController, so stale results never show up.
  • Results are built with textContent and announced to screen readers through aria-live.

“Can results show up while I type?” We hear it for product catalogues, knowledge bases and customer lists inside apps. The first version usually listens to input and calls fetch() every time. It feels fine locally. In production, an eight-letter word sends eight requests, and the response for “sho” can land after the one for “shoes”, leaving the wrong results on screen. Here’s how we fix it without a library.

Wait for a pause

Every keystroke restarts a timer, and the function only runs once the timer completes uninterrupted:

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

We usually start between 200 and 300 ms. Shorter still sends plenty of requests; longer makes the UI feel sluggish. Try it with real users, since the right value also depends on how fast your backend answers.

Don’t mix it up with throttle, which runs at most once per interval while the action continues. Throttle suits scroll and resize handlers; typing calls for debounce.

Abort what’s out of date

Debouncing cuts the number of calls but can’t stop an older response from arriving late. Keep a handle on the in-flight request and abort it before starting the next one:

const input = document.querySelector('#search');
const list = document.querySelector('#results');
const statusEl = document.querySelector('#search-status');
let controller;

const search = debounce(async (term) => {
  controller?.abort();
  if (term.length < 2) {
    list.replaceChildren();
    statusEl.textContent = '';
    return;
  }
  controller = new AbortController();
  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(term)}`, {
      signal: controller.signal,
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    render(await res.json());
  } catch (err) {
    if (err.name !== 'AbortError') statusEl.textContent = 'Search is unavailable right now.';
  }
}, 250);

input.addEventListener('input', () => search(input.value.trim()));

An AbortError is expected here: it means you cancelled on purpose, so don’t show an error for it. The two-character minimum avoids queries that would return half the database.

Render safely, for everyone

Titles come from the server, which often means from other users’ input. Dropping them in with innerHTML invites script injection, so build the elements instead:

function render(items) {
  list.replaceChildren(...items.map((item) => {
    const li = document.createElement('li');
    const a = document.createElement('a');
    a.href = item.url;
    a.textContent = item.title;   // never innerHTML with server data
    li.append(a);
    return li;
  }));
  statusEl.textContent = `${items.length} result(s)`;
}

Keep the markup a real form. Without JavaScript, or when someone presses Enter, it still leads to the regular results page:

<form action="/search" method="get" role="search">
  <label for="search">Search products</label>
  <input id="search" name="q" type="search" autocomplete="off">
  <p id="search-status" aria-live="polite"></p>
  <ul id="results"></ul>
</form>

The aria-live region tells screen reader users how many results there are, since they can’t see the list changing below the field.

On the server

Keep the endpoint lean: cap the number of results, return only title and URL, and index the columns you search. On large tables a LIKE '%term%' scans every row, which is when a full-text index or a dedicated search engine starts to pay off.

FAQ

Does debouncing protect my server?

Only from your own interface. Anyone can call the URL directly, so add server-side rate limiting if the endpoint is public.

Does this work with WordPress?

Yes. Point it at a dedicated REST route that returns only the fields you need, rather than the default search route, which sends back far more data.

Is your site search slow or returning the wrong things? We tune both the interface and the backend so people find what they’re looking for.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →