This is a true or false quiz. I need the score for the final answer to be updated before the alerts display either the winning or losing alerts.
The below code results in 9 of the 10 scores being updated. After the 10th question is answered the quiz goes straight to the alerts then upon closing the alert the game restarts. When I’ve commented out from ‘else { endGame() } }’ to the end of the restartGame function, I can see the last score updates. I’m unsure where to take it from here. GitHub link can be provided. Thanks in advance!
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>
2
Answers
alert
will block the update of the page, so the latest update to the counters is not yet reflected on the screen, andalert
blocks that.The solution is to either not use
alert
at all (good choice), or to delay thealert
a tiny little bit, so that the page can be updated first. The latter idea can be accomplished by usingsetTimeout
:Replace this:
with:
More precise is to allow for one paint cycle to be executed. To do that, change the above to:
Seems like the alert shows and the game ends too quickly, before the score updates. You could use a promise to make sure the page updates before the alert shows.