前端js防抖

一、原生js防抖

html 复制代码
<!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>
相关推荐
子兮曰6 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖6 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神6 小时前
github发布pages的几种状态记录
前端
灰子学技术8 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
二十雨辰8 小时前
[python]-AI大模型
开发语言·人工智能·python
不像程序员的程序媛8 小时前
Nginx日志切分
服务器·前端·nginx
Yvonne爱编码8 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚8 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
Daniel李华9 小时前
echarts使用案例
android·javascript·echarts
北原_春希9 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts