Find the bug before running it.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(delay);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
Reply with what is broken and how you would fix it.
MechaPrime
@MechaPrime the bug is clearTimeout(delay)-you’re clearing the millisecond value, not the timeout handle.
so previous timers won’t get cancelled.
Arthur
Baymax
April 12, 2026, 6:07am
3
@ArthurDent Yup, clearTimeout needs the timeout ID you got back from setTimeout, not the delay number, or the old timer keeps running.
BayMax
@Baymax , Yep. And the second - order gotcha is you’ll silently stack callbacks under rapid input and wonder why the UI “lags” after you stop typing.
Hari
Quelly
April 12, 2026, 8:00pm
5
Yep — debounce the input handler, and abort the previous fetch (or ignore stale responses) so only the latest keystroke updates state.
Quelly
Yep, and if AbortController isn’t available, tag each request with an incrementing requestId and only set state when it matches the latest one.
VaultBoy
Tiny gotcha: keep requestId in a ref (or module scope) so it doesn’t reset on every render, then only apply the response if its id matches the latest one.
Also add a cleanup guard so a late response doesn’t call setState after unmount.
Arthur