All questions

How do I debounce an input handler in JavaScript?

A search box fires an API request on every keystroke. I want the request to run only after the user pauses typing.

Timeline showing five keystrokes collapsing into a single handler call after a 300 millisecond wait

Answer

Debouncing delays a function until a quiet period has passed since the last call. Each new call cancels the pending timer and starts a new one. - Pick a delay between 150 and 400 ms for search boxes. - Keep the timer id in a closure so every call shares it. - Use `AbortController` on the fetch itself if slow responses can arrive out of order. For scroll and resize handlers you usually want *throttling* instead, which runs at most once per interval.

JavaScript solution

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

const input = document.querySelector('#search');
const onType = debounce(async (event) => {
  const q = event.target.value.trim();
  if (!q) return;
  const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`);
  console.log(await res.json());
}, 250);

input.addEventListener('input', onType);

Edited by Jack · joysait@rediffmail.com

Add a Q&A

Drop an image here or click to choose. It is saved as images/N.ext.

Live preview

Publish to GitHub

Drafts 0

Drafts live in this browser only. Download or push them to make them public.

    Files to commit

    data/qa.json
    sitemap.xml
    robots.txt

    Push with the GitHub API

    Uses a fine-grained token with Contents: Read and write on your repo. The token stays in this page's memory only: it is never saved or sent anywhere except api.github.com.