JS防抖函数加强版

JS防抖函数加强版

debounce(fn, wait = 500,immediate = false) {
    let timer = null
    let timer2 = null
    let times = 0
    return function(...args) {
        if (timer2) {
          clearTimeout(timer)
          clearTimeout(timer2)
        }
        // ------ 新增部分 start ------ 
        // immediate 为 true 表示第一次触发后执行
        // timer 为空表示首次触发
         if (immediate && !timer) {
             times++
             fn.apply(this, args)
         }
        // ------ 新增部分 end ------ 

         timer = setTimeout(() => {
            if(times == 0 ){
              times++
              fn.apply(this, args)
            }
         }, wait)
        timer2 = setTimeout(() => {
          times = 0
        },2000)
    }
  }

  

posted @ 2022-12-27 23:20  迷醉的小眼  阅读(35)  评论(0)    收藏  举报