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.