How does Javascript debounce work?

buttons

What is debounce?

A recent increasing popular technique in web applications is an interesting one. It is so called “debounce”. Debouncing in JavaScript is used to limit the rate at which a function can fire. It works by delaying the execution of a function until a certain amount of time has passed without it being called. This can be useful in cases where a function is called multiple times in a short period of time, such as when a user is typing into an input field, and you only want to perform an action after they have finished typing.

Debounce real world analogy

A real world analogy of debounce is to a physical button, once is pressed, it remains in the pressed state (.e.g stays in the housing socket) for a number period of time, during which cannot be pressed again since it is already in pressed down position, before it “bounces” back that can be pressed again.

Javascript implementation

To implement debouncing in JavaScript, you can use a function that sets a timer whenever it is called. If the function is called again before the timer has expired, the timer is cleared and reset, delaying the execution of the function until the timer has expired.

Here is an example of a debounced function in JavaScript:

1
2
3
4
5
6
7
8
9
function debounce(fn, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}

In this example, we have a debounce function that takes two arguments: a callback function fn and a delay time delay. It returns a new function that sets a timer whenever it is called, and calls the callback function only if the timer has expired and no further calls have been made to the returned function.

You can use this debounced function as a wrapper for any function that you want to limit the rate of execution.

1
const debouncedFunction = debounce(myFunction, 1000);

This code creates a new debounced function that calls the myFunction once per second at most.