何时显示TextContent的更改?



我正在为Odin项目制作石头/剪子/布游戏。我在div resultMsg中显示游戏结果,并在countMsg中显示基于该结果的运行计数。这两个项目都是HTML中的div,它们工作正常。在总共5场比赛输赢后,我想(按顺序)清除textContent消息,使用"alert"给出一个最终的计数,然后重新开始。

我原以为用"->"将清除textContent消息。然而,直到我点击[确定]清除警报后,它们才会显示。我很想知道这是为什么。

相关HTML正文:

<div id="playersChoice">
<button id='rock'>Rock</button>
<button id='paper'>Paper</button>
<button id='scissors'>Scissors</button>
</div>    

<div id="result">
</div>
<div id="count">
</div>

相关的Javascript。

let gamesPlayed = 0;
let playerWon = 0;
let computerWon = 0;
const countMsg = document.querySelector ('#count');
const resultMsg = document.querySelector ('#result');
// Get all the buttons within playerschoice container
const userButton = document.querySelectorAll ('#playersChoice > button');
// For each button, create an event listener for the click which will play a round.
// Note the Button.ID identifies the players choice.
userButton.forEach(button => {
button.addEventListener('click', function() {
gamesPlayed++;
resultMsg.textContent = playRound(button.id, computerPlay());
// if there are less than 5 clear wins or losses
if ((playerWon + computerWon) < 5) {
countMsg.textContent = "The current tally is your " + playerWon + " wins to the computers " + computerWon + ".";
} else {
// there have been 5 definitive games, declare the overall winner!
->          resultMsg.textContent = '';
->          countMsg.textContent = '';
gamesPlayed = 0;
playerWon = 0;
computerWon = 0;
alert("Best of 5 series results : You won " + playerWon +", lost " + computerWon + ", and tied "+ (5-playerWon-computerWon) + " of them.");
}
});
});
'''

alert()将阻止当前脚本执行,但它似乎也阻止了DOM更新。这就是为什么即使对textContent的分配在警报之前,文本也只在单击警报并恢复执行之后显示。

你可以使用一个非常小的setTimeout来允许DOM在alert()触发之前更新:

const div = document.querySelector("div");
function test1() {
div.textContent = "Test without timeout!";
alert("Test1!");
}
function test2() {
div.textContent = "Test with timeout!";
setTimeout(() => alert("Test2!"), 10);
}
<button onclick="test1()">Test</button>
<button onclick="test2()">Test with timeout</button>
<h4>Text content:</h4>
<div></div>

编辑:

我研究了更多,更准确地说,DOM更新只发生在脚本完成之后。由于alert()阻塞了当前脚本,DOM更新只会在警报被解除后发生。

这种行为也可以在下面的代码片段中看到:

function wait(ms) {
var start = Date.now(),
now = start;
while (now - start < ms) {
now = Date.now();
}
}
function test() {
document.querySelector("div").textContent = "Test with delay!";
wait(2000);
}
<button onclick="test()">Test with delay</button>
<div></div>

最新更新