前端经常会遇到连续调用事件的问题,所以节流函数和防抖函数是必不可少的。
我个人通常会在封装通用组件里包裹一层防止事件的重复调用。
节流函数
直接上代码
function throttle(fn, delay) {
let running = true;
return function () {
if (running) {
fn.apply(this, arguments);
console.log("arguments", arguments[0]);
running = false;
setTimeout(() => {
running = true;
}, delay);
}
};
}
function needThrottle() {
console.log("hihihi");
}
const test = throttle(needThrottle, 200);
test(1);
test(2);
test(3);
通过打印出的 arguments[0] 可以看出,执行的是第一次调用的函数。
防抖函数
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
console.log('arguments',arguments[0]);
timer = null;
}, delay);
};
}
const debounced = debounce(() => console.log("hi"));
debounced(1);
debounced(2);
debounced(3);
通过打印出的 arguments[0] 可以看出,执行的是最后一次调用的函数。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。