Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
JavaScript

JavaScript: Fix a Debounced Handler Dropping a Keystroke

- 28.11.26 - ErcanOPAK

⚡ Fix a Debounced Handler Dropping a Keystroke

A debounce wrapper only coalesces calls into one trailing invocation if every one of those calls reaches the same function instance – the one holding the actual timer ID in its closure. A common mistake in a component-based UI is creating that wrapper fresh on every render, with no memoization at all, so each keystroke is handled by a brand-new debounce instance that has never heard of the pending timer the previous instance already scheduled. clearTimeout only works against a timer ID the current closure actually has a reference to, so each new instance quietly lets the prior instance’s own pending call continue running on its own schedule – producing one delayed call per keystroke instead of a single one at the end, with no guarantee the calls resolve in typing order once more than one is in flight.

🔎 The Problem

function SearchBox() {
  const [query, setQuery] = useState('');

  // Re-created on every render - this is the bug
  const debouncedSearch = debounce((q) => runSearch(q), 300);

  return (
    <input
      value={query}
      onChange={(e) => {
        setQuery(e.target.value);
        debouncedSearch(e.target.value);
      }}
    />
  );
}

// Typing 'cat' fast:
// keystroke 'c'   -> NEW debounce instance #1, schedules timer A
// keystroke 'ca'  -> NEW debounce instance #2, schedules timer B
//                     (instance #2 has never seen timer A - can't clear it)
// keystroke 'cat' -> NEW debounce instance #3, schedules timer C
// All three timers (A, B, C) are independently still pending and will
// all eventually fire, each with whatever value it individually closed
// over - 'c', 'ca', and 'cat' - in whatever order the event loop
// actually resolves them, not necessarily in typing order

✅ Fix: Create the Debounced Function Once

  • Create the debounced function exactly once per component instance, with useRef or useMemo, so every keystroke shares the same timer state and clearTimeout can actually cancel the previous pending call.
  • Pass the latest value into the debounced call explicitly rather than relying on a closure over component state, so a shared debounce instance always acts on the most recent argument instead of whatever state existed when it was created.
  • Add a cleanup that cancels any pending debounced call on unmount (most debounce utilities expose a .cancel() method) so a component that unmounts mid-wait doesn’t fire a state update against a component that’s no longer there.

🚨 Why This Is Dangerous

A search box or autosave field that occasionally loses the last character or two typed before a pause is a strange enough symptom that it’s easy to blame the network, the backend, or a flaky test rather than a debounce wrapper that was never actually debouncing more than one keystroke at a time.

A debounce function only coalesces calls it can see – and a new instance created on every render has never seen anything that came before it.

— JavaScript Tip

Related posts:

JavaScript: Use Promises for Better Async Handling

JavaScript: Use Promises for Better Async Handling

How to get session value in Javascript

How to get session value in Javascript

JavaScript Functions Accidentally Reallocate Memory

JavaScript Functions Accidentally Reallocate Memory

Views: 6
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Windows 11: Fix a Touchpad’s Four-Finger Swipe Going Silent
Docker: Fix a Build Secret Leaking Into a Cached Layer

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com