Middle
What is the difference between debounce and throttle?
sobes.tech AI
Answer from AI
Debounce and throttle are techniques for controlling the frequency of function calls, often used to optimize events such as text input or scrolling.
-
Debounce delays the execution of a function until the event stops occurring for a specified period. In other words, the function will only be called once after the user has stopped performing the action.
-
Throttle limits the execution of a function, allowing it to be called no more often than once within a specified interval, regardless of how many times the event occurs.
Example:
// Debounce
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
// Throttle
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Debounce is suitable for search input, where you need to wait for the input to finish, while throttle is used for scroll events, where it is important to limit the frequency of calls.