šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

What is debouncing in Javascript

On the UI some user actions are expensive.

For example, a search operation can be expensive if we do it for every keypress. If the user types a word with 6 characters, and we search at every keyup event then we will have 6 API calls in a very short interval.

The fix would be to make the actual search only after the user had finished typing the search term. In other words, make the API call one second later after no key was pressed anymore for one second.

And this is were debouncing comes into play.

Debouncing makes sure that a function is not called again until a certain amount of time has passed without the function being called. Basically it limits the frequency of function calls.

For example, if the user is typing javascript we should search just for the jull word and not for:

  • j
  • ja
  • jav ...

Here is how one simple implementation of a debouncing function may look like:

function debounce(callback, time) {
    let interval;
    return () => {
        clearTimeout(interval)
        interval = setTimeout(() => {
                interval = null
                callback(arguments)
            }, time)
    }
}

Besides searching debouncing can be used with other expensive operations such as autosaving a form, resizing a window, scrolling or autocompleting a text input based on an API call.

You can find here the full working example and check also how to add debounce to useEffect() in React.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *