4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】処理中の入力待ち

Posted at

したいこと

メソッド内で処理を一旦止めて、画面のイベントの発火を待ちたい。

このようにするのだ

index.html
<!DOCTYPE html>
<html>
<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>JS 入力待ち</title>
</head>
<body>
    <div id="message"></div>
    <button onclick='onButtonClick("Yes")'>Yes</button>
    <button onclick='onButtonClick("No")'>No</button>
    <button onclick='alert("Hello!!")'>処理中も画面がフリーズせずに別の操作が行えるよ</button>

    <script src="main.js"></script>
</body>
</html>
main.js
const messageHtmlElement = document.getElementById("message");
let resolveButtonClick = null;

async function なんか処理() {
    messageHtmlElement.innerText = "処理中…";

    const result = await waitButtonClick();

    messageHtmlElement.innerText = result + "ボタンが押されました。";
}

function waitButtonClick() {
    return new Promise(resolve => {
        resolveButtonClick = resolve;
    });
}

function onButtonClick(str) {
    if (resolveButtonClick !== null) {
        resolveButtonClick(str);
    }
}

なんか処理();
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?