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 it being called.
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 resizing a window, scrolling or autocomplete 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.