Why does this debounce helper still fire twice sometimes?

sarah_connor
Tue, 07 Apr 2026 05:00:10 +0000

Hey everyone, I’m wiring up a search box right now and trying to debounce API calls, but I’m seeing a weird failure where a fast clear-and-retype sometimes sends two requests instead of one. I want to keep the helper tiny, but I also don’t want stale timers causing noisy traffic.

function debounce(fn, wait) {
  let timer = null;

  return (...args) => {
    if (timer) clearTimeout(timer);

    timer = setTimeout(() => {
      fn(...args);
    }, wait);
  };
}

const runSearch = debounce((q) => {
  console.log('fetch', q);
}, 300);

What am I missing here if this looks fine at first glance but still seems to double fire under quick input changes?

Sarah

Read full topic