防抖与节流

该文通过示例展示了JavaScript中防抖(debounce)和节流(throttle)函数的实现和应用,用于优化输入事件(如input)和鼠标移动事件(如mousemove)的处理,提高性能。防抖函数在连续触发时只执行最后一次,而节流函数在设定的时间间隔内保证至少执行一次。
摘要由CSDN通过智能技术生成

节流与防抖

<!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>
      .box,
      .argbox {
        width: 200px;
        height: 200px;
        background: #168fe6;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <h2>防抖函数封装</h2>
    <input type="text" class="input1" placeholder="请输入电话号码" />
    <h2>防抖函数传参数</h2>
    <input type="text" class="input2" placeholder="请输入电话号码" />
    <h2>节流函数封装</h2>
    <div class="box"></div>
    <h2>节流函数传参数</h2>
    <div class="argbox"></div>
    <script>
      // 防抖
      let telInput = document.querySelector('.input1');
      telInput.addEventListener('input', antiShake(demo, 2000));
      function antiShake(fn, wait) {
        let timeOut = null;
        return function () {
          if (timeOut) clearTimeout(timeOut);
          timeOut = setTimeout(() => {
            fn.apply(this, arguments);
          }, wait);
        };
      }
      function demo() {
        console.log('请求数据');
      }

      // 防抖传参
      function antiShakearg(e) {
        console.log('请求数据', e.target.value);
      }
      let telInputarg = document.querySelector('.input2');
      let antiShakeFunc = antiShake(antiShakearg, 2000);
      telInputarg.addEventListener('input', function (e) {
        antiShakeFunc(e);
      });

      // 节流
      let box = document.querySelector('.box');
      box.addEventListener('mousemove', throttle(demo, 2000));
      function throttle(event, time) {
        let timer = null;
        return function () {
          if (!timer) {
            timer = setTimeout(() => {
              event.apply(this, arguments);
              timer = null;
            }, time);
          }
        };
      }

      // 节流传参
      function demoarg(e) {
        console.log('请求数据', e.clientX, e.clientY);
      }
      let argbox = document.querySelector('.argbox');
      let throttleargFunc = throttle(demoarg, 2000);
      argbox.addEventListener('mousemove', function (e) {
        throttleargFunc(e);
      });
    </script>
  </body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值