DEV Community

Cover image for Debouncing in javascript✨
Aishanii
Aishanii

Posted on

Debouncing in javascript✨

To optimise browser performance as well as keep up with user experience deliverables, there are few techniques, one of which is debouncing.

A very fine example for this would be any search bar. When you type a word in search bar with every letter it shows new recommendations.

From the surface the trick here must be making an API call every time somebody enters a letter to fetch desirable options according to latest input.

A better way to do this is through debouncing,

  • We set a threshold for a time period, can be 5s or .05 sec.

  • Every time this threshold timer expires, we make an API call to get data best matching the input.

  • Clear the timer and reset

Code:

<input
className="search-bar"
onChange={ hecticSearchHandler }
/>
Enter fullscreen mode Exit fullscreen mode
function hecticSearchHandler(...args){

/* capture the search query entered by customer */
const { value } = args[0].target;

/* Make an API call with search query */
getSearchResults(value);
}
Enter fullscreen mode Exit fullscreen mode

Image description

Reusable function code:

const optiSearchHandler = debounceFunc(searchHandler, 500)

const debounceFunc = (func, delay) => {
   let timer;
    return function(...args) {
       const context = this;
       clearTimeOut(timer);
       timer = setTimeOut(() => {
           func.apply(context, args);
       }, delay)
     }
}
Enter fullscreen mode Exit fullscreen mode

Watch this video for clarity: Debounce interview ques

Top comments (2)

Collapse
 
brense profile image
Rense Bakker •

In React 18 you do not have to debounce anymore unless you really only want something to happen after a very specific amount of time. Otherwise you can use the new useDeferredValue hook: reactjs.org/blog/2022/03/29/react-...

Collapse
 
aishanipach profile image
Aishanii •

Sounds interesting.
Will definitely check this out!