防抖和节流

61 阅读1分钟

实现防抖和节流

防抖节流能有效的提高性能

function debounce(fn,wait = 500){
    let timer = null
    return function (){
        if (timer){
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn.apply(this,arguments)
        },wait)
    }
}
document.getElementById('_input').addEventListener('keyup',debounce(function (){
    console.log(this.value)
}))


// 防抖

function debounce(fn,wait=500,immediate=false){
   let timer = null;
   const _debounce = function(){ 
        const _args = [...arguments]
        if(timer){
            clearTimeout(timer)
        }
        if(immediate){
            let flag = timer === null
            timer = setTimeout(() => {
                timer = null
            }, wait);
            flag && fn.apply(this,_args)
        }else{
            timer = setTimeout(() => {
                fn.apply(this,_args)
            }, wait);
        }

   }

   _debounce.cancel = function () {
      clearTimeout(timer);
      timer = null;
    }

   return _debounce
}

function debounceTestFn(){
    console.log('debounceTestFn',this)
}

const debouncejubin = debounce(debounceTestFn,2000,true)
debouncejubin.call({a:1})
debouncejubin.call({b:1})
debouncejubin.call({c:1})
debouncejubin.call({d:1})
// debounceTestFn { a: 1 }



//节流---一段时间执行一次
function throttle(fn,wait=100){
    let timer = null
    return function (){
        if (timer) return
        timer = setTimeout(()=>{
            fn.apply(this,arguments)
            timer = null
        },wait)
    }
}