截流防抖

81 阅读1分钟

截流防抖 ———— 应付面试

  1. 截流(throttle)

    截流就是让一个函数(动作)在一段时间内只能发生一次

    const throttle = (fn, time) => { 
        let flag = false
        return (...args) => { 
            if(flag) return 
            fn(...args)   // fn.call(undefined, ...args) 
            flag = true 
            setTimeout(()=>{ 
                flag = false 
                }, time) 
            } 
        }
    

    使用方法

    const f = throttle(()=>{console.log('hi')}, 3000) 
    f() // 打印 hi 
    f() // 无效果,三秒后才可以打印
    

    上述代码中flag可以使用timer来代替,就可以少写一个参数

    const throttle = (f, time) => {
        let timer = null 
        return (...args) => { 
            if(timer) {return} 
            f(...args)  // f.call(undefined, ...args) 
            timer = setTimeout(()=>{ 
                timer = null 
                }, time) 
            } 
       }
    
  2. 防抖(debounce)

防抖就是每次触发一个动作(函数)都要再重新等一段时间才执行,同时打断上次出发的动作(函数)

const debounce = (fn, time) => { 
    let timer = null 
    return (...args)=>{ 
        if(timer !== null) { 
            clearTimeout(timer) // 打断fn
        } // 重新计时
        timer = setTimeout(()=>{ 
            fn.call(undefined, ...args) // timer结束后调用 fn 
            timer = null 
        }, time) 
    } 
}