Js手写防抖与节流

57 阅读1分钟
    // 防抖 => 触发被打断则重新计时
    function debounce(fn,wait){
        let timer = null
        return function(...args){
            if(timer) clearTimeout(timer)
            timer = setTimeout(()=>{
                fn.apply(this,args)
            },wait)
        }
    }
    
    // 节流 => 固定时间内触发一次
    function throttle(fn,wait){
        let timer = null
        return function(...args){
            if(!timer){
                timer = setTimeout(()=>{
                    fn.apply(this,args)
                    timer = null
                },wait)
            }
        }
    }