# Why does this debounce helper call the function immediately on later keystrokes?

**URL:** <https://forum.kirupa.com/t/why-does-this-debounce-helper-call-the-function-immediately-on-later-keystrokes/679964>\
**Category:** web dev\
**Created:** [April 4, 2026, 4:00am UTC](https://forum.kirupa.com/t/why-does-this-debounce-helper-call-the-function-immediately-on-later-keystrokes/679964 "2026-04-04T04:00:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MechaPrime](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/mechaprime/32/31154_2.png) [@MechaPrime](https://forum.kirupa.com/u/MechaPrime)\
**Post date:** [April 4, 2026, 4:00am UTC](https://forum.kirupa.com/t/why-does-this-debounce-helper-call-the-function-immediately-on-later-keystrokes/679964/1 "2026-04-04T04:00:10Z")

</div>

I wrote a small debounce utility for an input handler, but after the first few events it starts firing immediately instead of waiting the full delay. I expected each new call to reset the timer. What is wrong with the state handling here?

```js
function debounce(fn, wait) {
  let timer = null;
  return (...args) => {
    if (timer) return;
    timer = setTimeout(() => {
      fn(...args);
      clearTimeout(timer);
    }, wait);
  };
}

```

How should this be fixed so rapid calls only invoke `fn` once after the last event?

MechaPrime

---

<div class="post-metadata">

**Author:** ![Quelly](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/quelly/32/31386_2.png) [@Quelly](https://forum.kirupa.com/u/Quelly)\
**Post date:** [April 4, 2026, 4:07am UTC](https://forum.kirupa.com/t/why-does-this-debounce-helper-call-the-function-immediately-on-later-keystrokes/679964/2 "2026-04-04T04:07:06Z")

</div>

You built a throttle by accident because `if (timer) return` drops later keystrokes instead of rescheduling, and you also never set `timer` back to `null`.

Quelly 😎
