为什么用防抖和节流?
答:如果事件处理函数用的频率无限制,会加重浏览器和服务器的负担,此时我们就可以用防抖(debounce)和节流(throttle)的方式来减少调用频率,同时又不影响实际效果。
防抖:事件高频触发时 只执行最后一次
防抖的实现:
function _debounce(fn, delay) {
let time;
return function () {
if (time) clearTimeout(time);
time = setTimeout(() => {
fn.call(this);
}, delay);
};
}
节流: 在一定时间内,频繁触发一个事件时, 只触发一次函数
function throttle(fn, delay) {
let time = null;
return function () {
if (!time ) {
time = setTimeout(() => {
fn.call(this);
time = null;
}, delay);
}
};
}