DEV Community

Cover image for Let’s implement a Debounce function in Javascript
Alex
Alex

Posted on • Updated on • Originally published at blog.alexefimenko.com

Let’s implement a Debounce function in Javascript

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

Previously I used Lodash’s debounce function, so I didn’t know how it worked and decided to implement it myself. I think it would be a good exercise and maybe help someone else come up with a better understanding of how it works.

Check how debounce works:

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);
  };
}
Enter fullscreen mode Exit fullscreen mode

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.


I'm always open to making new connections! Feel free to connect with me on LinkedIn

Top comments (2)

Collapse
 
marmariadev profile image
Maria M.

Great article on debounce. Can you give tips on using debounce for dynamic search fields in web forms to enhance user experience?

Collapse
 
alexefimenko profile image
Alex • Edited

Thank you!
I wrote a new post about using the debounce function for search in React.
Hope you'll find it useful!