Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

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

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Fix a Debounced Function Still Firing Once per Call Instead of Once per Burst Because the Timer Variable Is Declared Inside the Returned Function Instead of the Outer Closure

- 04.11.26 - ErcanOPAK

⚡ Fix a Debounced Function Still Firing Once per Call Instead of Once per Burst Because the Timer Variable Is Declared Inside the Returned Function Instead of the Outer Closure

A correct debounce implementation relies on one shared timer identifier that persists across every call to the debounced function, so each new call can cancel the pending timeout left over from the previous one before scheduling its own. That sharing only works if the timer variable lives in the outer factory function’s closure, declared once when the debounced function is created. Declaring let timer inside the function that actually gets called and returned, instead of in the function that creates and returns it, means a brand new, independent timer variable is created fresh on every single call — clearTimeout(timer) at the top of the function has nothing from a previous call to actually cancel, because that previous call’s timer variable already went out of scope the moment it returned.

🔎 The Problem

// Bug: timer declared inside the returned function
function debounce(fn, delay) {
  return function (...args) {
    let timer;                 // <- new variable every single call
    clearTimeout(timer);       // <- always clearing a timer that was
                                //    just created undefined; never the
                                //    previous call's actual timer
    timer = setTimeout(() => fn(...args), delay);
  };
}
// Result: every call schedules its own independent timeout.
// Calling it 5 times in a row fires fn 5 times, each `delay` after
// its own call - not once, `delay` after the last call.

✅ The Fix

  • Move the timer variable’s declaration up into the outer function — the one that runs once and returns the debounced function — so the same variable is captured by the closure and shared across every call instead of being recreated each time.
  • Add a quick manual test: call the debounced function several times in rapid succession and count how many times the wrapped function actually runs — a correct debounce runs it exactly once, well after the last call, not once per call.
  • If you reach for a utility library’s debounce instead of writing your own, you get this closure handled correctly for free — worth it specifically because this exact bug is easy to introduce and easy to miss in a quick glance at otherwise-reasonable-looking code.

🚨 Why This Is Dangerous

  • A debounce that silently degrades into firing on every call still looks like it’s working in a slow, deliberate manual test with single, well-spaced clicks — it only reveals itself under the rapid, bursty input (fast typing, a dragged slider) that debouncing was supposed to be protecting against in the first place.

A debounce is only as shared as its timer variable — put that variable in the wrong scope and every call gets its own private, useless copy of the thing that was supposed to be shared.

— JavaScript Tip

Related posts:

JavaScript: Use Optional Chaining to Avoid Cannot Read Property Errors

JavaScript: Use Optional Chaining to Avoid Cannot Read Property Errors

JavaScript: Use ?? Instead of || for Default Values

JavaScript: Use ?? Instead of || for Default Values

JavaScript: Fix a String.replace() Call That Silently Only Replaces the First Match Because the Rege...

JavaScript: Fix a String.replace() Call That Silently Only Replaces the First Match Because the Rege...

Views: 9

Post navigation

Ajax: Fix a Long-Polling Request Silently Piling Up Duplicate Connections Because the Previous One Was Never Aborted Before Starting the Next
C#: Fix an Async Iterator Silently Not Running Any of Its Code Until the First MoveNextAsync Call Because IAsyncEnumerable Enumeration Is Fully Lazy

Leave a Reply Cancel reply

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

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (607)
  • Average of all values in a column that are not zero in SQL (569)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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