1.抖动
触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次触发,则重新计算时间。
const debounce = (fn, time) => {
let timer = null;
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
}, time);
}
};
2.节流
高频事件触发,但n秒内只会执行一次,所以节流会稀释函数的执行频率。跟抖动的区别在于节流n秒内一定会执行一次。
const throttle = (fn, time) => {
let available= true;
return function() {
if (!available) return;
available= false;
setTimeout(() => {
fn.apply(this, arguments);
available= true;
}, time);
}
}