防抖和节流

防抖

多次触发事件,只有最后一次会执行。

代码示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>防抖的学习</title>
  </head>
  <body>
    <input id="inp" />
  </body>

  <script>
    /**
     * 防抖节流中apply里面的this很关键
     * 加上 apply this 确保 在 sayHi 函数里的 this 指向的是 input对象(不然就指向 window 了,不是我们想要的)。这里的箭头函数依旧是指向 input 对象。
     * 如果return的不是function,而是箭头函数,那this就绑定无效了,一定要是function,打印的话function的this是<input id="inp">,() => {}是window{...}
     * @param fn
     * @returns {Function}
     */
    function debounce(fn) {
      let timer = null; // 创建一个标记用来存放定时器的返回值

      // 如果return的不是function,而是箭头函数,那this就绑定无效了,一定要是function,打印的话function的this是<input id="inp">,() => {}是window{...}
      return function () {
        clearTimeout(timer); // 每当用户输入的时候把前一个 setTimeout clear 掉
        timer = setTimeout(() => {
          // 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
          fn.apply(this, arguments);
        }, 1000);
      };
    }
    function sayHi() {
      console.log('防抖成功');
      console.log(this); // this指向调用者window
    }

    var inp = document.getElementById('inp');
    inp.addEventListener('input', debounce(sayHi)); // 防抖
  </script>
</html>

节流

每间隔一段时间内,只会触发一次。

© 2022  Arvin Xiang
Built with ❤️ by myself