防抖和节流的区别是什么?(demo演示)

共同点

共同点:在高频触发事件中限制触发频次,减少不必要的内存耗费

区别

防抖(debounce)处理:n秒内多次触发只执行最后一次触发(若一直触发,只执行最后一次触发)
节流(throttle)处理:n秒内多次触发只执行第一次触发(若一直触发,每隔n秒触发一次)

示例

  • input事件节流处理
  • window.resize事件防抖
<!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>
    <style>
      .box1 {
        border: 1px solid red;
        padding: 20px;
      }
      .box2 {
        border: 1px solid blue;
        padding: 20px;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <div class="box1">
      <h1>节流场景(input事件)</h1>
      <input id="input" type="text" oninput="handleInput()" />
      <p id="inputValue"></p>
    </div>
    <div class="box2">
      <h1>防抖场景(监听窗口变化)</h1>
      <p id="screenHeightValue"></p>
    </div>
  </body>
  <script>
    //节流
    function throttle(fn, delay) {
      let run = true;
      return function () {
        if (!run) return;
        run = false;
        setTimeout(() => {
          fn.apply(this, arguments);
          run = true;
        }, delay);
      };
    }
    const handleInput = throttle(() => {
      const value = document.getElementById("input").value;
      document.getElementById("inputValue").innerText = value;
      console.log("输入了", value);
    }, 1000);

    //防抖
    function debounce(fn, delay) {
      let timer = null;
      return function () {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(fn, delay);
      };
    }
    window.addEventListener(
      "resize",
      debounce(() => {
        const screenHeight = document.documentElement.clientHeight;
        document.getElementById("screenHeightValue").innerText = screenHeight;
        console.log("窗口变化了", screenHeight);
      }, 500)
    );
  </script>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值