throttle节流函数
在delay时间内,只保留第一次的执行结果
能够控制请求的数量
适用于onscroll、onresize、mouseover等事件
function throttle(Fn, delay = 500){
let last = new Date();
return function(...args){
let now = new Date();
if(now - last > delay){
Fn.apply(this, args);
last = now;
}
}
}
// 使用定时器的写法
function throttle2(fn, delay = 500){
let timer = null;
return function(){
if(timer){
return;
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}