Debounce: chỉ gọi hàm sau khi ngừng trigger một khoảng thời gian (dùng cho search input, resize).
- Throttle: gọi hàm tối đa một lần trong khoảng thời gian nhất định (dùng cho scroll, mousemove).
- Debounce = 'đợi nghỉ', throttle = 'giới hạn tần suất'.
javascript
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
function throttle(fn, interval) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= interval) { last = now; fn(...args); }
};
}