节流函数

function throttle(fn, delay) {
let lastTime;
let timer;
delay = delay || 300;
return function() {
let args = arguments;
// 记录当前函数触发的时间
let nowTime = Date.now();
if (lastTime && nowTime - lastTime < delay) {
clearTimeout(timer);
timer = setTimeout(function() {
// 记录上一次函数触发的时间
lastTime = nowTime;
// 修正this指向问题
fn.apply(this, args);
}, delay);
} else {
lastTime = nowTime;
fn.apply(this, args);
}
};
}
posted @ 2022-04-28 15:17  莣ㄋ噯  阅读(24)  评论(0)    收藏  举报