Javascript を使用したデバウンスとスロットリングについて

13964 ワード

これらのデバウンスまたはスロットリングのいずれかを何回使用しなければならなかったか思い出せません.これらは、実生活で使用されるすべてのアプリに必要です.

それでは、デバウンス機能から始めましょう.デバウンス機能は、オートコンプリートなどによく使用する機能です.そのように説明します.

チェックアウト用の住所オートコンプリート機能を構築したいと想像してください.デバウンス機能なしでどのように機能するかを見てみましょう.

<!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 and Throttle</title>
  </head>
  <body>
    <input id="debounce" type="text" placeholder="debounce" />

    <script>
      document.getElementById("debounce").addEventListener(
        "keydown",
        (e) => {
          console.log(e.target.value);
        }
      );
    </script>
  </body>
</html>


とても簡単ですよね?しかし、サービスが通話ごとに課金される場合、またはサーバー上でサービスを実行していて IT チームを泣かせたくない場合はどうなるでしょうか?そこでデバウンス機能が活躍します.

<!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 and Throttle</title>
  </head>
  <body>
    <input id="debounce" type="text" placeholder="debounce" />

    <script>
      const debounce = (func, wait) => {
        let timeout;

        return (...args) => {
          if (timeout) clearTimeout(timeout);

          timeout = setTimeout(() => func(...args), wait);
        };
      };

      document.getElementById("debounce").addEventListener(
        "keydown",
        debounce((e) => {
          console.log(e.target.value);
        }, 1000)
      );
    </script>
  </body>
</html>


これで、ユーザーが 1 秒間入力を停止した後にのみ実行されます.誰もが満足しています!

しかし、API を 2 秒ごとに 1 回しか呼び出せないという制限があるとします.それがスロットル機能の仕事です!それなしでどのように実装されるか見てみましょう:

<!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 and Throttle</title>
  </head>
  <body>
    <button type="button" id="throttle">throttle</button>

    <script>

      document.getElementById("throttle").addEventListener(
        "click",
        () => {
          console.log("clicked");
        }
      );
    </script>
  </body>
</html>


まあ、不安なユーザーはあなたのアプリケーションを壊す可能性があります!スロットラー関数を使用してそれを防ぐ方法を見てみましょう.

<!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 and Throttle</title>
  </head>
  <body>
    <button type="button" id="throttle">throttle</button>

    <script>
      const throttle = (func, wait) => {
        let lastTime = 0;

        return (...args) => {
          const now = Date.now();

          if (now - lastTime >= wait) {
            func(...args);

            lastTime = now;
          }
        };
      };

      document.getElementById("throttle").addEventListener(
        "click",
        throttle(() => {
          console.log("clicked");
        }, 2000)
      );
    </script>
  </body>
</html>


すごいですよね?これらの関数は、実際の問題を解決するのに本当に役立ちます!