防抖与节流

防抖

  • 概述:在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。
      // 防抖
      const debounce = (fn, delay, ...args) => {
        let timeout;
        return function () {
          if (timeout) clearTimeout(timeout);
          timeout = setTimeout(() => {
            fn(args);
          }, delay);
        };
      };

应用:搜索框,窗口大小变化监测、滑动事件等

节流

  • 概述:单位时间内有事件被多次触发则只生效一次。即在规定的时间内,函数只能被调用一次,且是最先被触发调用的那次。
      // 节流
      const throttle = (fn, delay, ...args) => {
        let lastTime = 0;
        return function () {
          let nowTime = Date.now();
          if (nowTime - lastTime > delay) {
            fn(args);
            lastTime = nowTime;
          }
        };
      };

应用:高频点击、表单重复提交、滚动加载等。

总结

  • 完整代码如下:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>防抖与节流</title>
  </head>
  <body>
    <button id="content">点击触发</button>

    <script>
      // 防抖
      const debounce = (fn, delay, ...args) => {
        let timeout;
        return function () {
          if (timeout) clearTimeout(timeout);
          timeout = setTimeout(() => {
            fn(args);
          }, delay);
        };
      };

      // 节流
      const throttle = (fn, delay, ...args) => {
        let lastTime = 0;
        return function () {
          let nowTime = Date.now();
          if (nowTime - lastTime > delay) {
            fn(args);
            lastTime = nowTime;
          }
        };
      };

      // 测试代码
      function testFunction(...args) {
        console.log("args:", args);
        console.log("防抖完成");
      }
      window.onload = function () {
        var myDebounce = document.getElementById("content");
        myDebounce.addEventListener(
          "click",
          throttle(testFunction, 1000, "hello")
          // debounce(testFunction, 300, "hello")
        );
      };
    </script>
  </body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值