Let’s implement a Debounce function in Javascript

A debounce function is used to limit the rate at which a function can fire.

The most common way to implement a debounce function is to use Lodash’s debounce function (opens in a new tab). Lodash is a popular Javascript utility library that provides a lot of useful functions. It is a great library, but it is also a big library. If you are not using Lodash in your project, you can implement a debounce function yourself.

Debounced function delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.

Check how debounce works:

Regular execution

Debounced execution


Clicks: 0

Count: 0

Real-life examples

  • Doing an API call on every keypress in an input. If the user types fast, we will fire a lot of API calls, which is not good. We can use debounce to limit the rate at which the API calls are made.
  • A button click is handled by a function that will only run once in a given period, such as the Save button. If the user clicks the button multiple times, we will only run the function once.
  • When a user resizes a window or scrolls a page, which can trigger dozens or hundreds of calls in a small period of time.

Implementing a debounce function is not that hard. Two key concepts are used: closures and setTimeout.

export function debounce(callback: () => void, interval: number) {
  let timeout: number | null = null
  return function (...args: unknown[]) {
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => callback(...args), interval)

Closure is a function that has access to the parent scope, even after the parent function has closed. In our case, the parent function is the debounce function and the child function is the function that will be called after the wait time has passed. The child function will have access to the parent function’s scope, even after the parent function has closed.

SetTimeout is a function that will call a function after a given time has passed. SetTimeout returns a timer ID that can be used to cancel the timer by calling the clearTimeout function. We will use this to reset the timer if the function is called again before the wait time has passed.