手撕防抖函数

109 阅读1分钟

简易版防抖:

const debounce(fn,delay){

let timeOut;

return function(){

clearTimeout(timeout)

timeOut = setTimeOut(()=>{fn.apply(this,arguments)}),delay}

}

是否立即执行的防抖:

const debounce(fn,delay,ifNow){

let timeOut;

return function(){

if(timeOut)clearTimeout(timeout)

if(ifNow){

let callNow = !timeOut

timeOut = setTimeOut(()=>{timeOut = null},delay)

if(callNow){

fn.apply(this,arguments)}

}else{

timeOut = setTimeOut(()=>{fn.apply(this,arguments)}),delay}

}

}