Spot the bug - #1

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

@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

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