JavaScript でイベント待ちする方法

JavaScript でイベント待ちする方法

例えば Window.alert() のように、ユーザがボタンをクリックするまでの間、処理を止めたい場面があったとします。

このとき、パッと思いつくのは、

  1. ビジーウェイトする方法
  2. Promise の解決を待つ方法

です。(間違いなく後者を採用すべきです。)


それぞれのコード例を掲載します。

いずれのコードも、ボタンが押下されたら後続の処理が開始され、コンソールにメッセージが出力されます。

ビジーウェイトする方法 #

<!DOCTYPE html>
<html>
  <body>
    <button id="button">Button</button>
  </body>

  <script type="text/javascript">
    const button = document.getElementById("button");

    let pushed = false;

    button.addEventListener("click", () => (pushed = true));

    while (pushed === false) {}

    console.log("Execute subsequent processes.");
  </script>
</html>

Promise の解決を待つ方法 #

<!DOCTYPE html>
<html>
  <body>
    <button id="button">Button</button>
  </body>

  <script type="text/javascript">
    const button = document.getElementById("button");

    const clickWaiter = () =>
      new Promise((resolve) => button.addEventListener("click", resolve));

    const main = async () => {
      await clickWaiter();
      console.log("Execute subsequent processes.");
    };

    main();
  </script>
</html>