这是一个对错测验。我需要在警报显示获胜或失败警报之前更新最终答案的分数。
以下代码会更新 10 个分数中的 9 个。回答完第 10 个问题后,测验将直接进入警报,然后关闭警报后游戏将重新开始。当我从 'else { endGame() } }' 注释到 restartGame 函数的末尾时,我可以看到最后的分数更新。我不确定从这里到哪里去。可以提供 GitHub 链接。预先感谢!
function loadQuestion() {
const currentQuestion = questionsAnswers[questionIndex];
document.getElementById("question-box").innerHTML = currentQuestion.question;
}
let correctScore = 0;
let incorrectScore = 0;
function checkAnswer() {
const currentQuestion = questionsAnswers[questionIndex];
const correctAnswer = currentQuestion.correctAnswer;
console.log(correctAnswer)
if (userAnswer === correctAnswer) {
console.log(questionsAnswers[questionIndex]);
correctScore++;
}
if (userAnswer != correctAnswer) {
console.log(questionsAnswers[questionIndex]);
incorrectScore++;
}
document.getElementById("correct-score").textContent = correctScore;
document.getElementById("incorrect-score").textContent = incorrectScore;
questionIndex++;
if (questionIndex < questionsAnswers.length) {
loadQuestion();
} else {
endGame()
}
}
//once all ten questions have been answered the player is told if won or lost and invited to play again
function endGame() {
if (correctScore === 10) {
alert("Congratulations - you won!")
} else {
alert("Unlucky, you didn't win this time - play again!")
}
restartGame()
}
function restartGame() {
questionIndex = 0;
correctScore = 0;
incorrectScore = 0;
document.getElementById("correct-score").textContent = correctScore;
document.getElementById("incorrect-score").textContent = incorrectScore;
loadQuestion();
}
<div>HTML Here please!</div>
alert
将阻止页面更新,因此计数器的最新更新尚未反映在屏幕上,alert
会阻止该更新。
解决方案是要么根本不使用
alert
(不错的选择),或者稍微延迟 alert
,以便可以先更新页面。后一个想法可以通过使用 setTimeout
: 来实现
替换这个:
} else {
endGame()
}
与:
} else {
setTimeout(endGame, 50);
}
更精确的是允许执行一个绘制周期。为此,请将上面的内容更改为:
} else {
requestAnimationFrame(() => requestAnimationFrame(endGame));
}