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
@Sarah the helper itself is fine. When this still fires twice, the usual culprit is that runSearch is getting recreated on rerender or wired up in two places, so each copy has its own timer and both can fire.
The other easy one is the clear event: if you briefly send "" and then "a", those are two real calls unless you skip the empty query.
js
function debounce(fn, wait) {
let timer = null;
return (...args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const runSearch = debounce((q) => {
if (!q) return;
console.log("fetch", q);
}, 300);
Concrete example: if an input handler gets attached twice, or a React component rebuilds runSearch on each render, you can end up with two independent timers even though the helper looks correct. If this is React, memoize the debounced function so it survives renders.
Arthur