120.节流和防抖,Vue中如何添加节流和防抖

一、什么是防抖、什么是节流

试想以下场景:

  • 1、疯狂滑动网页,如果要求在每一瞬间滑动的时候,都触发某个函数?
  • 2、和一个人争论,对方在喋喋不休地开炮,这个时候,你是等对方讲完再来讲道理,还是等她安静下来呢?

很多时候,我们不需要实时地去反馈。这对机器的性能要求太高了,并且不太必要,所以有了以下的解决方案:

  • 1、防抖:假定一个停顿时间,如果下一个操作和上一个操作的间隔不够一个停顿时间,我们就取消操作的想法。

    等喋喋不休的人彻底(并不是永远,而是泛指一段规定的时间内)安静下来,我们再阐述道理。

  • 2、节流:假定一个间隔时间,在持续操作的时候,按照间隔的时间触发。

    有间隔地回复喋喋不休的人。

二、防抖示例(从原理上看,防抖就是要把之前的事件清空掉,所以是比节流简单很多的)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
<style>
  html, body, ul, li {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .wrap ul {
     800px;
    height: 500px;
    background-color: #eee;
    overflow-y: scroll;
  }
  .wrap ul li {
     100%;
    height: 100px;
    margin-bottom: 10px;
    background-color: #089e8a;
  }
  .wrap ul li:last-child {
    margin-bottom: 0;
  }
</style>
</head>
<body>
  <div class="wrap">
    <ul id="ul">
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>7</li>
      <li>8</li>
      <li>9</li>
      <li>10</li>
    </ul>
  </div>
</body>
<script>
  window.onload = function () {
    // 获取滚动父元素
    const oUl = document.getElementById('ul')
    // 编写防抖函数
    const fn = function (delay) {
      let timeout = null
      return function() {
        if (timeout) {
          window.clearTimeout(timeout)
        }

        timeout = setTimeout(() => {
          console.log('执行 scroll 的回调')
          arguments.callee(delay)
        }, 1000)
      }
    }
    oUl.addEventListener('scroll', fn(1000))
  }
</script>
</html>

接下来我们可以尝试着优化我们的 JS 部分,让停顿下来后,需要执行的函数,与我们实现防抖的部分分离。

window.onload = function () {
  // 获取滚动父元素
  const oUl = document.getElementById('ul')
  // 编写防抖函数
  const debounce = (fn, delay) => {
    let timeout = null
    return () => {
      if (timeout) {
        window.clearTimeout(timeout)
      }
      timeout = setTimeout(fn, delay)
    }
  }
  oUl.addEventListener('scroll', debounce(() => {
    console.log('我是防抖的事件')
  }, 1000))
}

上面的写法没办法帮我们把 event 传进去,这里我们要把当前的作用域也传进去

window.onload = function () {
  // 获取滚动父元素
  const oUl = document.getElementById('ul')
  // 编写防抖函数
  const debounce = (fn, delay) => {
    let timeout = null
    return () => {
      const me = this
      const args = arguments
      if (timeout) {
        window.clearTimeout(timeout)
      }
      timeout = setTimeout(() => {
        fn.apply(me, args)
      }, delay)
    }
  }
  oUl.addEventListener('scroll', debounce(function(event) {
    console.log('event', event)
  }, 1000))
}

三、节流函数的示例(节流函数相对来说较难,但只要理解了闭包的关键点,就还好)

window.onload = function () {
  // 获取滚动父元素
  const oUl = document.getElementById('ul')

  // 编写节流函数
  const throttle = (fn, threshold) => {
    let timeout = null
    // 这里是闭包的关键,它存储在内存中,帮我们记录
    let last = new Date()
    threshold = threshold || 500
    return () => {
      const me = this
      const args = arguments
      let now = new Date()
      /*
        * 第一次进入,进入 setTimeout
        * 节流时间内进入,走 else,删掉上一次的 timeout
        * 一直到节流时间后进入,直接进入 if 块里面,直接执行
        */
      clearTimeout(timeout)
      if (now - last >= threshold) {
        fn.apply(me, args)
        last = now
      } else {
        timeout = setTimeout(() => {
          fn.apply(me, args)
        }, threshold)
      }
    }
  }
  oUl.addEventListener('scroll', throttle(function(event) {
    console.log('event', event)
  }, 1000))
}

老实说:直接手写的话,还是要理解透彻点,不然写不出来。或者,多写几次。

四、在 Vue 项目中better-scroll组件中用debounce函数

以下函数仅是部分代码,像better-scroll这样的组件有传 pos 的记得要把相应的参数传进去。

下面用的 debounce 即是我们上面的。

methods: {
  scrollHandler(pos) {
    console.log('pos.y', pos.y)
  },
  initScroll() {
    this.scroll.on('scroll', (pos) => {
      debounce(this.scrollHandler.apply(this, [pos]))
    })
  },
}


参考文档

知乎——函数防抖与函数节流


complete.

原文地址:https://www.cnblogs.com/can-i-do/p/13062167.html