New to Rust? Grab our free Rust for Beginners eBook Get it free →
Debounce Function JavaScript: How to Build One

When a JavaScript task responds to a burst of events, you may want its callback to wait until the calls pause. Debouncing combines calls that arrive close together and runs the callback after they pause.
I’ll show how to build a debounce function and compare its behavior with throttle.
TL;DR
A debounce wrapper delays a callback until no new call arrives during its wait interval.
- Store the timeout identifier inside a closure so each call can cancel the pending timer.
- Forward the latest arguments and, when needed, the calling object as this.
- Use throttle instead when work should continue at intervals during ongoing activity.
What Is a Debounce Function in JavaScript?
Debouncing combines calls that arrive close together and runs the callback after the calls pause. A returned wrapper keeps one timer and restarts it whenever another event arrives before the timer expires.
A closure retains the timer identifier between calls. The comparison probe showed trailing behavior emits a value after each pause. A debounce function is higher-order because it accepts a function and returns a timed wrapper.
For a search field, the handler can run per keystroke while suggestions wait until typing stops.
| Term | What happens | Typical fit |
|---|---|---|
| Trailing debounce | Runs after calls stop for the wait interval | Search suggestions after typing |
| Leading debounce | Runs at the start of a burst | Immediate response, with later calls suppressed |
| Throttle | Allows calls at set intervals during activity | Periodic scroll or pointer updates |
How to Debounce a Function Step by Step
A trailing wrapper handles this task with one saved timer and a callback. I used the plain version because the example’s output shows the final value after the pause.
Step 1: Keep the timer in a closure
The delay uses milliseconds. A busy event loop can make the callback run later than requested.
function debounce(fn, delay) {
let timerId;
return function (...args) {
const context = this;
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(context, args), delay);
};
}
setTimeout returns the timer identifier, and clearTimeout cancels its pending callback. The rest parameter gathers arguments for the later call. apply supplies the saved receiver when a method reads its object’s fields.
Step 2: Wrap the work that should wait
This example sends search terms close together and checks which value reaches the callback.
const search = debounce((term) => console.log(`Search: ${term}`), 40);
search("j");
search("ja");
search("javascript");
A second check stores callback values in an array, calls the wrapper twice before the wait expires, then reads the result.
setTimeout(() => {
const values = [];
const collect = debounce((value) => values.push(value), 20);
collect("first");
collect("last");
setTimeout(() => console.log(`Calls: ${values.length}; value: ${values[0]}`), 35);
}, 55);
In my run, the command node debounce_demo.js printed these exact lines:
Search: javascript Calls: 1; value: last

The last term appears, and the check records one callback. A browser input handler can pass its current field value to request suggestions.
Keep the wrapper outside the handler so each keystroke can replace the same pending callback. Type a query, pause, and confirm one callback receives the completed text.
Debounce Edge Cases and Throttle
Choose behavior for the task, accounting for missing callbacks and long bursts.
| Case | Observed behavior or risk | Response |
|---|---|---|
| Callback is missing | The delayed call raises a TypeError | Pass a function to debounce() and validate inputs at the API boundary |
| Calls keep arriving | Trailing execution keeps moving later | Choose leading execution or a max-wait feature when periodic progress is required |
| Method uses this | Calling the callback without its original receiver loses object state | Save the wrapper’s receiver and use fn.apply(context, args) |
| Delay exceeds timer range | Browser timers have a signed 32-bit delay limit | Keep waits within the documented range and split longer schedules |
Passing undefined as the callback produced “TypeError: fn is not a function.” Pass a callable function before creating the wrapper.

A leading call can suit a button that should respond at once. Lodash provides leading and trailing options, cancellation, flushing and a maximum wait.
I ran node debounce-vs-throttle.js. Debounce waits for a pause, while throttle permits periodic calls during activity.
Debounce trailing calls: 20,70,100 Throttle interval calls: 0,60,100

Choose the JavaScript throttle function when ongoing updates must arrive at intervals. Calls that keep arriving inside the wait interval can postpone trailing work, so a library’s maximum-wait option can provide occasional progress.
Conclusion
Use this wrapper for trailing work, and choose a library when cancellation or maximum wait matters. It returns before its callback runs, so a synchronous caller cannot use that eventual return value. Set the wait to balance repeated work against delay after input ends.
For more JavaScript context, see CodeForGeek’s guide to JavaScript callbacks and other interview topics. The MDN debounce glossary, setTimeout(), and clearTimeout() references explain the browser timer behavior.
FAQ
These answers clarify common choices when adding debounce to an event handler.
Is debounce a higher-order function?
Yes. A debounce function accepts a function and returns a new function that controls when the original function runs.
What is the alternative to debounce in JavaScript?
Throttle is a common alternative when a callback should run at intervals during continuing events instead of waiting for a pause.
Does debounce use the latest arguments?
This implementation forwards the arguments from the latest call that resets the timer.




