Throttle giới hạn call rate xuống tối đa một lần mỗi interval — gọi ngay lần đầu rồi chặn.
js
function throttle(fn, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}Khác debounce: throttle gọi ngay lần đầu rồi chặn, debounce đợi hết delay mới gọi.
Dùng cho scroll, mousemove.
function throttle(fn, limit) { let inThrottle; return (...args) => { if (!inThrottle) { fn(...args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } Difference from debounce: throttle fires immediately then blocks, debounce waits for the delay to finish before firing.
Use for scroll, mousemove events.