防抖和节流实现

我记得我之前不是写过防抖节流吗?
5PUTQH.md.jpg

防抖(debounce)

      debounce(fn, wait) {
        let timer = null
        return function() {
          timer && clearTimeout(timer)
          timer = setTimeout(() => {
            fn.apply(this, arguments)
          }, wait)
        }
      }

节流(throttle)

      throttle(fn, time) {
        let oldTime = Date.now()
        return function() {
          let nowTime = Date.now()
          if(nowTime - oldTime > time) {
            fn.apply(this, arguments)
            oldTime = nowTime
          }
        }
      }

实战运用

posted @ 2021-10-07 15:32  卿六  阅读(35)  评论(1编辑  收藏  举报