最初にキャンセルを押した後にこのコードが「キャンセルしました」と表示されないのはなぜですか?setTimeoutで小さなタイムアウトで同期機能が実行されない
「hi」の表示を許可しないボックスを確認します。
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "hi";
setTimeout(confirmOperation, 0, "Please, press a button!");
}
function confirmOperation(message) {
var txt;
if (confirm(message) == true) {
txt = "You pressed OK!";
document.getElementById("demo").innerHTML = txt;
return true;
} else {
txt = "You pressed Cancel!";
document.getElementById("demo").innerHTML = txt;
setTimeout(confirmOperation, 0, "Please, press a button!");
return false;
}
}
</script>
</body>
</html>
DOMの再描画でテキストを置き換える時間を許さないconfirmOperationを直ちに実行するため – epascarello