防抖
防抖是多次触发函数,只有最后一次执行函数,每次触发函数重新计时。使用闭包封装如下
const debounce = (fn, delay) => {
let timer = null;
return function () {
const context = this;
const args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
};
使用方法如下:
// 实例化函数对象,这样子timer才不会销毁
const the = debounce(fn, 400);
......
// 调用函数
the("zczczc");
......
节流
节流是多次触发某个函数,只需要第一次执行。使用闭包进行封装如下
const throttle = (fn, delay) => {
// last为上一次触发回调的时间, timer是定时器
let last = 0;
let timer = null;
return function () {
const context = this;
const args = arguments;
const now = +new Date();
if (now - last < delay) {
last = now;
clearTimeout(timer);
timer = setTimeout(() => {
last = 0;
timer = null;
}, delay);
} else {
last = now;
fn.apply(context, args);
}
};
};
使用方法如下:
// 实例化函数对象,这样子last和timer才不会销毁
const the = throttle(fn, 400);
......
// 调用函数
the("zczczc");
......