防抖
含义
对于短时间内连续触发的事件,防抖的含义就是让某个时间期限内,时间处理函数只执行一次。
代码
function debounce(fn,delay){
let timer = null;
return function() {
if(timer) {
clearTimeout(timer);
}else{
timer = setTimeout(fn,delay);
}
};
}
节流
含义
在函数执行一次之后,该函数在执行时间内不再工作
代码
function throttle(fn,delay) {
let valid = true;
return function() {
if(!valid) {
return false;
}
valid = true;
setTimeout(()=>{
fn();
valid = false;
},delay);
};
}