Concept of Debounce and Throttle
Debounce and Throttle are two commonly used high-order functions in our development. In a word, the above two serve for avoiding a certain function being called to many times in a certain time range.
In our daily usage, these two functions are usually used in the below scenarios like in the front-end development, the listener for the mouse event, scrolling and other high-frequent events. Since some listeners require much calculation time and will lead to a stall and frozen in the display. Thus, to give a better User Experience, we need to use the debounce and throttle to reduce performance compensation.
Since the two concepts are quite close, we should discuss the two first. The Debounce is that we set a timer whenever an event is triggered, and we hold the event's callback function until the timer approaches the limit. Also, if the timer is not done, and a new event is triggered we need to reset the timer.
The Throttle is to set a timer as well, and we want specific callbacks must be called under this time limit.
Here we can see the significant difference between the Debounce and Throttle is that Throttle guarantees that one callback must be triggered under a delta T while the Debounce won't.
Implementation
Then we can look into the implementation of Throttle and Debounce:
Debounce:
let debounce = (fn, wait) => {
wait = wait || 0;
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, wait);
}
}
The above code shows how to do a simple debounce with a certain time limit (called wait). You can also try it via CodePen:
We can see from the comparison that the debounce will help a lot to boost the process of handling events.
Throttle:
let throttle = (fn, wait) => {
wait = wait || 0;
let timer = null;
return (...args) => {
if (!timer)
timer = setTimeout((args) => {
clearTimeout(timer);
timer = null;
fn.apply(this, args);
}, wait);
}
}
Conclusion
From the above demo and implementation, we can tell that the debounce and throttle will be a very helpful method when we are dealing with high frequent operations like mouse events listening or so. It will reduce the redundant methods calling to get a better performance.