防抖
防抖,以最新的事件触发为时间起点,在固定时间后执行方法。
举个通俗易懂的例子,电梯1秒内没有检测到有人经过门口,即开始关闭,如果在一秒内有新的人进入电梯,则电梯重新开始计时,时间间隔仍为1秒,1秒后,无人进入电梯,则电梯门开始关闭。
// debounce函数
// Fn为执行函数
// delay为防抖时间间隔
function debounce(Fn, delay) {
let timer = null;
return function () {
// 如果之前已经有一个timer在执行,则清除前一个定时器
// 在后面重新定义一个定时器
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
// 改变this指向
Fn.apply(this, arguments);
}, delay);
};
}
const test = debounce((x, y) => {
console.log(x, y);
}, 2000);
// 此次执行被丢弃
test(1, 2);
// 最终执行
test(2, 4);
节流
节流,指固定时间内,只执行一次。且执行第一次触发的函数。
如1秒内有3次执行,但是最终只能执行一次。
function throttle(Fn, delay) {
let timer;
return function () {
// 如果之前已经有一次执行,则不需要做任何处理
// 它会执行第一次触发的函数
if (timer) {
return;
}
timer = setTimeout(() => {
Fn.apply(this, arguments);
// 执行完,清除定时器
clearTimeout(timer);
}, delay);
};
}
const test = throttle((x, y) => {
console.log(x, y);
}, 2000);
// 最终执行
test(1, 2);
// 此次执行被丢弃
test(3, 4);