Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 35 ยท Projects

Project: Live Search with Debounce and Loading States

Build a live search box in Svelte 5 - debounced input, cancelling stale requests with AbortController, loading, empty and error states, highlighting and keyboard navigation.

Search-as-you-type is in almost every product: a command palette, a product filter, a user picker. It looks easy and hides several traps: firing a request per keystroke, results arriving out of order, no feedback while loading, no message when nothing matches, and no keyboard support. In this project you will build it properly and see how Svelte's reactivity keeps the code short.

The Svelte compiler is not available here, so Svelte files are read-only. The <TryIt> blocks run the real logic in plain JavaScript: a debounce helper, a fake slow API with AbortController and a complete searchable demo you can edit.

Requirements

  1. Typing in the box searches after a short pause (debounce), not on every key.
  2. Only the latest query's results are shown, even if an older request finishes later.
  3. Show Loading, Error (with retry), No results and Results states.
  4. Highlight the matched text.
  5. Arrow keys and Enter select a result; the box is properly labeled for screen readers.
stateDiagram-v2
  [*] --> Idle
  Idle --> Loading: query typed (after debounce)
  Loading --> Results: ok
  Loading --> Empty: ok, 0 items
  Loading --> Error: failed
  Error --> Loading: retry
  Results --> Loading: query changed
  Empty --> Loading: query changed

Every query change starts a new request; older ones are cancelled.

Debounce

A debounced function waits until its caller has been quiet for N milliseconds, then runs once with the latest arguments:

JS debounce: many keystrokes, one call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Six keystrokes become one call. 200 to 300 ms is a comfortable delay for most search boxes.

The Svelte component

In Svelte 5 an $effect that reads query re-runs whenever the query changes, and the function it returns is its cleanup, which runs before the next run. That is the perfect place to cancel the previous request and timer:

HTML
<!-- src/lib/LiveSearch.svelte -->
<script>
  let query = $state('');
  let status = $state('idle');     // 'idle' | 'loading' | 'ok' | 'error'
  let results = $state.raw([]);
  let active = $state(-1);

  $effect(() => {
    const q = query.trim();
    if (q.length < 2) {
      status = 'idle';
      results = [];
      return;
    }

    const controller = new AbortController();
    const timer = setTimeout(async () => {
      status = 'loading';
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: controller.signal });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        results = await res.json();
        active = -1;
        status = 'ok';
      } catch (err) {
        if (err.name !== 'AbortError') status = 'error';
      }
    }, 250);

    return () => {           // cleanup: runs before the effect re-runs, and on destroy
      clearTimeout(timer);
      controller.abort();
    };
  });

  function onkeydown(e) {
    if (e.key === 'ArrowDown') { active = Math.min(active + 1, results.length - 1); e.preventDefault(); }
    if (e.key === 'ArrowUp')   { active = Math.max(active - 1, 0); e.preventDefault(); }
    if (e.key === 'Enter' && results[active]) choose(results[active]);
    if (e.key === 'Escape')    { query = ''; }
  }

  function choose(item) {
    query = item.title;
  }

  function parts(text) {            // split text into [{text, hit}] around the query
    const q = query.trim();
    const i = text.toLowerCase().indexOf(q.toLowerCase());
    if (i === -1 || !q) return [{ text, hit: false }];
    return [
      { text: text.slice(0, i), hit: false },
      { text: text.slice(i, i + q.length), hit: true },
      { text: text.slice(i + q.length), hit: false },
    ];
  }
</script>

<label for="q">Search lessons</label>
<input
  id="q"
  type="search"
  bind:value={query}
  {onkeydown}
  role="combobox"
  aria-expanded={status === 'ok' && results.length > 0}
  aria-controls="results"
  aria-activedescendant={active >= 0 ? `r${active}` : undefined}
  autocomplete="off"
/>

<div role="status" aria-live="polite">
  {#if status === 'loading'}Searching...
  {:else if status === 'ok'}{results.length} result{results.length === 1 ? '' : 's'}
  {/if}
</div>

{#if status === 'error'}
  <p role="alert">Something went wrong. <button onclick={() => (query = query + ' ')}>Retry</button></p>
{:else if status === 'ok' && results.length === 0}
  <p>No lessons match "{query}".</p>
{:else if results.length > 0}
  <ul id="results" role="listbox">
    {#each results as item, i (item.id)}
      <li id="r{i}" role="option" aria-selected={i === active}>
        <button type="button" onclick={() => choose(item)}>
          {#each parts(item.title) as p}{#if p.hit}<mark>{p.text}</mark>{:else}{p.text}{/if}{/each}
        </button>
      </li>
    {/each}
  </ul>
{/if}

Why it works:

  • The effect depends on query. Every keystroke runs the cleanup of the previous run first, which clears the timer (debounce) and aborts an in-flight request (no stale results). AbortError is not a real error, so we ignore it.
  • results uses $state.raw because it is replaced wholesale and never mutated (see Debugging and Performance).
  • status is one variable describing which UI to show, so the markup is a simple {#if} chain instead of several booleans that can contradict each other.
  • The role="status" region announces the count to screen readers without moving focus, as described in Svelte Accessibility.
  • Highlighting is done by splitting text into parts and rendering <mark> elements. Avoid {@html} with user text: it invites XSS.

The out-of-order problem

Without the abort, a slow response for "sv" can arrive after the response for "svelte" and overwrite it. This simulation shows the bug and the fix. The fake API takes longer for shorter queries:

JS Stale responses: bug and fix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without cancellation the screen ends up showing results for "sv" while the box says "svelte". With AbortController, only the latest request can finish.

A runnable version

This demo wires the same ideas into a page: a debounced input, a fake API with random delay and occasional failure, loading/empty/error states, highlighting and arrow-key navigation.

Live search demo (plain JavaScript)

Ideas to extend it

  • Cache results by query in a Map so going back is instant.
  • Move the API into a SvelteKit +server.js endpoint, or search in the URL with ?q= and a load function so results are shareable.
  • Add a "recent searches" list stored per user.
  • Write a component test that types into the box and expects an option role to appear.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does debouncing do to a search box?

    A debounce resets its timer on each call and fires only after the delay passes with no new calls.
  2. 2. Why return a function from the $effect?

    Effect cleanup runs before the effect re-executes and when the component is destroyed.
  3. 3. What problem does AbortController solve here?

    Aborting the previous fetch guarantees only the latest request can update the results.
  4. 4. Why is a single status variable better than several booleans?

    One value naming the current state makes impossible combinations impossible.

Summary

  • Debounce input, then cancel stale work: in Svelte 5 an $effect with a cleanup function handles both neatly.
  • Use AbortController so only the latest query can update the UI.
  • Model the UI with one status value and render each state: idle, loading, results, empty, error.
  • Add accessibility from the start: a label, role="status" announcements and keyboard navigation.
  • Render highlights as elements, not with {@html} on user text.

Next: Project: A Markdown Blog with SvelteKit