JavaScript / HTML / CSS JavaScript Free

JavaScript: Debounce a Search Input

Stop firing a search request on every keystroke — debounce the input so it only searches after the user pauses typing.

24 lines · Updated Nov 26, 2026

Preview of JavaScript: Debounce a Search Input
javascript-debounce-search.js
<!-- <input type="text" id="search" placeholder="Search products..."> -->
<script>
function debounce(func, wait) {
    var timeout;
    return function () {
        var args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            func.apply(null, args);
        }, wait);
    };
}

var searchInput = document.getElementById('search');

var runSearch = debounce(function (query) {
    console.log('Searching for:', query);
    // fetch('/api/search?q=' + encodeURIComponent(query)) ...
}, 300);

searchInput.addEventListener('input', function (event) {
    runSearch(event.target.value);
});
</script>

About this snippet

A search box that sends a request on every keystroke hammers your server: typing "laptop" fires six requests, five of them useless. Debouncing waits until the user pauses typing — typically 300 milliseconds — and then runs the search once. This snippet is a tiny, reusable debounce function in plain JavaScript, wired up to a search input.

How it works

  1. debounce() takes a function and a wait time and returns a new function.
  2. Every time the new function is called, it cancels the previously scheduled call with clearTimeout() and schedules a fresh one with setTimeout().
  3. Only when calls stop for the full wait time does the original function actually run — with the latest arguments.

How to use it

  • Wrap your search function: the input's input event calls the debounced version.
  • Inside the search function, fetch results from your API and render them.
  • Encode the query with encodeURIComponent() when building the URL.

Choosing the delay

  • 200–300 ms feels instant for search-as-you-type.
  • 500 ms or more suits expensive operations like saving drafts.

Debounce vs throttle

Debounce runs once after activity stops — ideal for search boxes and window resize handlers. Throttle runs at most once every X milliseconds during activity — ideal for scroll tracking and progress bars.

Common problems

  • Old results appear after new ones: a slow earlier request finished last. Cancel previous requests with an AbortController, or ignore out-of-date responses.
  • Empty query sends a request: skip the search when the input is empty or shorter than 2 characters.

Related: Eloquent search scope (the server side) · Live search with Livewire

How to install

Paste the script after your search input. Change 300 to the wait time in milliseconds, and replace the console.log with your real search call.

Share this snippet

See all
Chat with us