防抖、节流函数的使用场景以及实例

92 阅读1分钟

防抖: 函数在事件触发时间段之后(或者之前)再调用,当还未超过当前时间段则重新计算时间段
场景:窗口的缩放,频繁缩放不进行计算,停止后再计算的高度或者宽度

let debounce = function(fun,wait){
          let timeOut  
          return function(){
            let args = arguments
            let that = this
            if (timeOut) clearTimeout(timeOut);
            timeOut = setTimeout(()=>{
                fun.apply(that,args)
              },wait)
          }
      }

节流: 减少事件触发调用函数的频率
场景: 搜索框,滚动条的触发事件,mousemove事件

 // 节流函数
    let throttle = function(fun,wait){
        // 减少事件触发调用函数的频率
        let timeout
        return function(){
            let that = this
            let args = arguments
            // 如果是在时间段内重新不执行函数
            if(!timeout){
                timeout = setTimeout(()=>{
                    timeout = null
                    fun.apply(that,args)
                },wait)
            }
        }
    }