js手写系列之节流

125 阅读1分钟

什么是节流(throttle)

节流是指单位时间内该事件只能触发第一次

参考lodash的throttle

    lodash.throttle(func, [wait=0], [options=]

简单实现不考虑参数

    function throttle(fn,wait=0){
        let start = new Date()
        
        return function (){
            const now = new Date()
            if(now - start > wait){
                fn()
            }
        }
    }

考虑参数

    function throttle(fn,wait=0){
        let start = new Date()
        return function (){
            const now = new Date()
            if(now - start > wait){
                fn.apply(this,arguments)
                start = new Date()
            }
        }
    }