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.

TermWhat happensTypical fit
Trailing debounceRuns after calls stop for the wait intervalSearch suggestions after typing
Leading debounceRuns at the start of a burstImmediate response, with later calls suppressed
ThrottleAllows calls at set intervals during activityPeriodic 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
Terminal output showing one debounced search call with the latest value

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.

CaseObserved behavior or riskResponse
Callback is missingThe delayed call raises a TypeErrorPass a function to debounce() and validate inputs at the API boundary
Calls keep arrivingTrailing execution keeps moving laterChoose leading execution or a max-wait feature when periodic progress is required
Method uses thisCalling the callback without its original receiver loses object stateSave the wrapper’s receiver and use fn.apply(context, args)
Delay exceeds timer rangeBrowser timers have a signed 32-bit delay limitKeep 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.

Terminal showing the TypeError caused by a missing debounce callback

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
Terminal comparing trailing debounce calls with throttle interval calls

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.

Pankaj Kumar
Pankaj Kumar

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 337