🐴 记住了,节流(throttle)与防抖(debounce)

136 阅读2分钟

window.scroll 遇到sber,那是反复触发反复折磨。

不单单是scroll,还有resize,还有一系列鼠标事件mousemovemouseover、你来说几个moverenter

还有啥,鼠标的事件,还有那个啥键盘的事件。自己查一查看一看瞧一瞧过过脑。


有些人很急,有些人事很多,来回转轱辘。不是ta不好,是我不对,我还做得不够好不够牛,导致人家有钻子找我麻烦千百遍来回。

于是我被B出来了,出来个throttle

还出了个debounce

顺便说一下,input的input事件去查接口也要加上,免得来回请求接口轱辘轴转。


throttle

直接上代码吧。

function throttle(fn, interval) {
  let last = 0
  
  return function () {
    let context = this
    let args = arguments
    let now = +new Date() // 加号将Date()对象转数字(时间戳),等于 new Date().getTime()
    
    if (now - last >= interval) {
      last = now;
      fn.apply(context, args)
    }
  }
}

咋个用法:

const myScroll = throttle(() => console.log('来了老弟'), 1000)

document.addEventListener('scroll', myScroll)

就咋说呢,就是滚动到点了,再做事情,不到点你就瞎做呗,不理你。就这意思。不到点休想支使我休想使唤我。

debounce

function debounce(fn, delay) {
  let timer = null
  
  return function () {
    let context = this
    let args = arguments
    
    if (timer) {
      clearTimeout(timer)
    }
    
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay)
  }
}

咋用:

const myScroll = debounce(() => console.log('来了老弟'), 1000)

document.addEventListener('scroll', myScroll)

还不好,比如说有个人,狂点,不等setTimeout做完事,这间隔中间又点了几个,等于又加了几个setTimeout,,这中间有多少个setTimeout计数器在等。

所以不好。

两者一结合,强强联合 throttle 和 debounce 强强结合

function stronger(fn, delay) {
  let last = 0, timer = null
  
  return function () {
    let context = this
    let args = arguments
    let now = +new Date()
    
    if (now - last < delay) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now
        fn.apply(context, args)
      }, delay)
    } else {
      last = now
      fn.apply(context, args)
    }
  }
}

用吧,跟上面那样用。

用吧,不好用你🐴 我。

闭包

它俩就是闭包。

完事。

祝你成功,不成功也行,祝你有花不尽的钱花,不用抠抠搜搜的过一生。