前端js防抖

一、原生js防抖

<!DOCTYPE html>
<html>
<head>
  <title>防抖按钮示例</title>
</head>
<body>
  <button id="immediateButton">立即触发</button>
  <button id="waitButton">等候触发</button>

  <script>
    function debounceImmediate(func, delay) {
      let timeoutId;
      let immediate = true;

      return function (...args) {
        clearTimeout(timeoutId);

        if (immediate) {
          func.apply(this, args);
          immediate = false;
        }

        timeoutId = setTimeout(() => {
          immediate = true;
        }, delay);
      };
    }

    function debounceWait(func, delay) {
      let timeoutId;

      return function (...args) {
        clearTimeout(timeoutId);

        timeoutId = setTimeout(() => {
          func.apply(this, args);
        }, delay);
      };
    }

    function handleImmediateClick() {
      console.log('立即触发按钮点击事件处理函数');
      // 在这里执行立即触发逻辑
    }

    function handleWaitClick() {
      console.log('等候触发按钮点击事件处理函数');
      // 在这里执行等候触发逻辑
    }

    const debouncedImmediateClick = debounceImmediate(handleImmediateClick, 1000); // 创建立即触发的防抖函数
    const debouncedWaitClick = debounceWait(handleWaitClick, 1000); // 创建等候触发的防抖函数

    const immediateButton = document.getElementById('immediateButton');
    immediateButton.addEventListener('click', debouncedImmediateClick);

    const waitButton = document.getElementById('waitButton');
    waitButton.addEventListener('click', debouncedWaitClick);
  </script>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值