js 函数防抖与节流

防抖内部实现原理:

// 函数防抖的内部实现
function debounce(fn,delay){
let timerId = null;
return function (){
const context = this;
if(timerId){
window.clearTimeout(timerId);
}
timerId = setTimeout(()=>{
fn.apply(context,arguments);
timerId = null;
},delay)
}
}

// 截流一段时间点击一尺
function throttle(fn,delay){
let canUse = true;
return function (){
if(canUse){
fn.apply(this,arguments);
canUse = false;
setTimeout(() => {
canUse = false
},delay);
}
}
}

posted @ 2020-03-12 15:07  小北,,,,小南  阅读(101)  评论(0)    收藏  举报