前端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>

你可能感兴趣的:(前端,javascript,开发语言)