js手写系列之防抖

263 阅读1分钟

1.什么是防抖

防抖是指当一个事件触发后要等待一段时间后才会执行,当等待期间该事件又被触发,则等待时间要重新计算,也就是说单位时间内连续触发执行最后一个代码

参考lodash的debounce

    /*
    *@ func 回调函数 function
    *@ wait number 函数等待触发的时间 可选 默认0
    *@ options 可选参数,防抖的一些可配置选项,逻辑比较复杂且不常用,暂时忽略
    *@ return 返回值是一个function
    */
    lodash.debounce(func, [wait=0], [options=])

最简单的防抖函数(不考虑传参)

    function debonce(func,wait=0){
        let timeId = null
        return funciton (){
            if(timeId){
                clearTimeout(timeId)
            }
            timeId = setTimeout(func,awit)
        }
    }

考虑函数传参

    function debonce(func,wait=0){
        let timeId = null
        return funciton (){
           
            if(timeId){
                clearTimeout(timeId)
            }
            
            timeId = setTimeout(()=>{
                func.apply(this,arguments)
            },wait)
            
        }
    
    }