JavaScript
常见代码片段
Debounce&throttle

debounce&throttle(防抖与节流)

<!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>debounce&throttle</title>
  </head>
  <body>
    debounce:<span id="debounce"></span>
    <br />
    throttle:<span id="throttle"></span>
    <br />
    <input type="text" id="input" />
    <script>
      const debounce = (fn, delay) => {
        let timer;
        return function (...args) {
          timer && clearTimeout(timer);
          timer = setTimeout(() => {
            fn.apply(this, args);
          }, delay);
        };
      };
 
      const throttle = (fn, delay) => {
        let timer;
        return function (...args) {
          if (!timer) {
            timer = setTimeout(() => {
              timer = null;
              fn.apply(this, args);
            }, delay);
          }
        };
      };
 
      const debounce_output = document.getElementById("debounce");
      const throttle_output = document.getElementById("throttle");
      const input = document.getElementById("input");
 
      const debounceLog = debounce((text) => {
        debounce_output.innerText = text;
      }, 1000);
 
      const throttleLog = throttle((text) => {
        throttle_output.innerText = text;
      }, 1000);
 
      input.addEventListener("input", (e) => {
        debounceLog(e.target.value);
        throttleLog(e.target.value);
      });
    </script>
  </body>
</html>