Debouncing is a important when you are making a scalable web product and going to JavaScript interview.
Introduction
Debouncing, is an important practice which is used very often by web developers to improve the performance of browser.
Debounce methods do not execute when invoked. Instead, they wait for a predetermined time before executing. If the same method is called again, the previous is cancelled and the timer restarts.
Example
Consider the example in this the function associated to the button will be called 2 sec after the button is pressed. No matter how many times you press is continuously it will be executed once.
Let us understand the code
function debounce(func, wait, immediate) {
var timeout;
return function executedFunction() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Here the debounce function takes three argument
- The function which needs to be executed.
- The wait time.
- do you want to invoke this immediately (optional).
we can also implement this in react very easily with help of lodash
Consider someone is building a search application making an api call after every key stroke. consider this example with help of debouncing you can visualize the difference between events fired.
Let's understand the code
onSearchItemWithDebounce = debounce((query) => {
this.setState({
queryWithDebounce: query
}, () => {
//Do Stuff after state is updated.
console.log('search with Debounce: ', this.state.queryWithDebounce);
})
this.setState({eventsFiredDebounce : this.state.eventsFiredDebounce+ 1})
}, WAIT_TIME);
**Note : debounce is imported from lodash**
Thanks for Bearing,
I will be writing articles explaining each hook provided by react in upcoming articles please follow to stay connected.
Top comments (7)
What is even more useful is to debounce based not only on time but on wether the underlying async operation you're doing is done. Shameless plug :)
Introducing the Async Debounce pattern
Rémy 🤖 ・ Dec 18 '18 ・ 5 min read
Very useful and cool but not quite seeing the benefit of the immediate parameter if the goal is to just debounce
What if you don't want to denounce, then use the immediate parameter.
thanks, that it's very useful
Great and short intro to debounce.
You can simplify the denounce function in your first example, using more modern JS syntax 😊
There's a great example here
freecodecamp.org/news/javascript-d...
Thanks For sharing
Some comments have been hidden by the post's author - find out more