Debounce and Throttling are both techniques used to control the rate at which a function is executed, especially in scenarios where a function might be called many times in a short span(like scrolling, resizing, keypresses e.t.c)
Here is a breakdown of the two with an example.
Debounce
Definition: Debounce ensures that a function is called only once after a specified delay has passed since the last time the function was invoked.
Use case: Ideal for situations like search input where you only want to trigger the search after the user has stopped typing.
Example
function debounce(func, delay){
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// usage
const handleInput = debounce(function (e) {
console.log('Search for:', e.target.value)
}, 300);
document.getElementById("search").addEventListener("input", handleInput);
Throttling
Definition: Throttling ensures that a function is called at most once every specified interval, no matter how many times the event occurs.
Use case: Useful for scroll events or window resizing, where you want to periodically handle the event, not every single time it fires.
Example
function throttle(func, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
//usage
const handleScroll = throttle(function (){
console.log('Scroll event at', new Date().toISOString());
}, 1000);
window.addEventListener("scroll", handleScroll);
Top comments (0)