Shaking prevention: When the task is frequently triggered, the task will be executed only when the interval triggered by the task exceeds the specified interval. It is generally used for real-time search in the input box. Similar to getting on the elevator, the elevator will run within 2 seconds after entering the elevator, and then it will run again after 2 seconds when someone enters the elevator again

<body> <button> </button> <script>function onAction() {
      console.log("Anti-shake function");
    }

    function debounce(fn, time) {
      let timer = null;
      return function () {
        if (timer) {
          clearTimeout(timer);
        }
        setTimeout(fn, time);
      }
    }
    const oDebounce = debounce(onAction, 2000);
    document.addEventListener('click',oDebounce);
  </script>
</body>
Copy the code

Throttling: Throttling specifies that a function is executed only once in a specified interval, typically for scroll events

<body> <button> Throttle function </button> <script>function onAction() {
      console.log("Throttle function");
    }

    function throttle(fn, time) {
      let canRun = true;
      return function () {
        if (canRun == false) {
          return;
        }
        canRun = false;
        setTimeout(() => {
          fn();
          canRun = true;
        }, time);
      }
    }
    const oThrottle = throttle(onAction, 2000);
    document.addEventListener('click', oThrottle);
  </script>
</body>
Copy the code