防抖-debounce:当一段时间内持续触发事件,只会执行最后一次。在延迟时间内,被触发,将刷新延迟时间。
const debounce = function(fn, delay){
let timer = null;
return (...args)=> {
clearTimeout(timer); //在此触发时,会清除上次的事件。
timer = settimeout(()=>{
fn.apply(this,argus);//fn调用参数
},delay);
};
}
节流-throttle:高频次数触发,在指定时间只会执行一次
function throttle(fn,delay=500){
let canrun = true; //可以执行
return function(){
if(!canrun) return ;//执行一次延迟时,就会变为false,后面的就会返回空。
canrun = false;
settimeout(()=>{
fn.apply(this,arguments); //argumens相当于下例子的e,每个函数都有,而上面的防抖是箭头函数只能用 ...arg形式来接收参数。
canrn = true;
},500);
};
}
function sayHi(e) {
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));
上述返回的均为一个函数,开头定义的timer,canruan只定义了一次。