Samgao0312 / Blog

MIT License
1 stars 1 forks source link

【再学前端】什么防抖和节流?有什么区别?如何实现? #137

Open Samgao0312 opened 2 years ago

Samgao0312 commented 2 years ago

image

是什么

实现防抖函数

事件被触发时,在n秒后执行函数,在n秒内多次触发事件,则重新开始计时。 利用定时器来实现,在 n 秒内多次触发,则先清除定时器,再重新计时。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
    window.onload = function() {
      // 定义一个防抖函数
      function debounce(fn, delay) {
        let timeout;
        return function () {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            fn.apply(this, arguments);
          }, delay);
        };
      }

      // 定义一个请求函数
      function request(val) {
        console.log('request: ' + val);
      }

      let debounceInput = debounce(request, 1000);

      let inputEl = document.getElementById('input');
      inputEl.addEventListener('keyup', function (e) {
        console.log('keyup: ', e.target.value)
        debounceInput(e.target.value);
      });
    }
    </script>
  </head>

  <body>
    <input type="text" id="input">
  </body>
</html>

实现节流函数

在规定的单位时间段内,函数只能执行一次,在单位时间内多少触发,则只有一次有效。 定时器来实现,当一个定时器执行,就会生成一个定时器id,当这个 id 存在就说明在单位时间内函数只执行了一次。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      window.onload = function () {
        // 定义一个节流函数
        function throttle(fn, delay) {
          let timer;
          return function () {
            if (!timer) {
              fn.apply(this, arguments);
              timer = setTimeout(() => {
                clearTimeout(timer);
                timer = null;
              }, delay);
            }
          };
        }
        // 定义一个请求函数
        function request(val) {
          console.log('request: ' + val);
        }
        let throttleInput = throttle(request, 1000);

        let inputEl = document.getElementById('input');
        inputEl.addEventListener('keyup', function (e) {
          throttleInput(e.target.value);
        });
      };
    </script>
  </head>

  <body>
    <input type="text" id="input" />
  </body>
</html>

区别

应用场景

防抖(debounce):

1,搜索输入框搜索内容,用户在不断的输入的时候,用防抖来节约请求资源。 2,不断的触发 window的resize事件,不断的改变窗口大小,利用防抖函数来只执行一次。

节流(throttle):

1,鼠标不断的点击,用节流来限制只在规定的单位时间内执行一次函数。 2,滚轮事件, 不断的往下滚轮,比如滚动到底部加载数据。

参考阅读