Разница
- Debounce — вызвать функцию только после паузы с последнего вызова (подождать «тишины»).
- Throttle — вызывать не чаще, чем раз в интервал.
Debounce (поиск по мере ввода)
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
Throttle (scroll / resize)
function throttle(func, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
Итог: debounce — «после остановки»; throttle — «не чаще N мс».