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); }
};
}Debounce: only calls the function after triggering has stopped for a given time period (use for search input, resize).
- Throttle: calls the function at most once per given time interval (use for scroll, mousemove).
- Debounce = 'wait for a pause', throttle = 'limit frequency'.
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); }
};
}