How can I debounce a function call in JavaScript?
Rashid D
rashid d profile pic

Debouncing is a technique used to limit the frequency of function calls, particularly in scenarios where the function may be invoked frequently, such as handling events triggered by user interactions like scrolling, resizing, or typing. Debouncing ensures that a function is only executed after a certain amount of time has passed since the last invocation. Here's an example of how to debounce a function call in JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12

function debounce(func, delay) {
  let timeoutId;

  return function (...args) {
    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

In this example, thedebounce function accepts two parameters:func, the function to be debounced, anddelay, the amount of time to wait before invoking the function. Within thedebounce function, atimeoutId variable is declared to keep track of the timer set bysetTimeout. The returned function is an anonymous function that wraps the original function. Inside the returned function,clearTimeout(timeoutId) is called to clear any previously set timers. This ensures that the function is only called once the specified delay has passed since the last invocation. Then, a new timer is set usingsetTimeout. When the timer expires, the original functionfunc is invoked usingfunc.apply(this, args) to maintain the correct context and pass any arguments provided. Here's an example of how to use thedebounce function:

1
2
3
4
5
6
7
8
9

function handleResize() {
  console.log('Resizing...');
  // Do something expensive here
}

const debouncedResize = debounce(handleResize, 200);

window.addEventListener('resize', debouncedResize);

In this example, thehandleResize function is debounced using a delay of 200 milliseconds. When theresize event is triggered on the window, thedebouncedResize function is called instead. The actualhandleResize function will only be executed once the user has finished resizing the window, and 200 milliseconds have elapsed since the last resize event. Debouncing can be applied to various scenarios where frequent function calls need to be throttled to improve performance and optimize resource usage. It's worth noting that there are also libraries like Lodash or Underscore.js that provide pre-built debounce functions that you can use, saving you from implementing it yourself. Keep in mind that the debounce technique can impact the real-time responsiveness of your application. Adjust the delay parameter appropriately to balance responsiveness and performance based on your specific use case.