Reputation: 5210
Real strange problem I'm having. I have this simple guessing game that asks four questions. It takes user input with an alert, prints to the DOM whether the user guessed correctly or incorrectly, and then displays an image (green checkbox or red x), THEN moves onto the next question. And so on, and so forth.
PROBLEM: The game runs, prints the message to the DOM, but does not show the images until the entire game is over.
What is strange is that the chrome console clearly shows that the "src" attribute of the img elements are being modified properly (and the file tree is correctly arranged to access the images). Instead, a blank box shows up. Until the end of the game, of course.
Sample of what my HTML looks like:
<p id="question1" class="rightAnswer" class="wrongAnswer"></p>
<img id="img1" src="" width="100">
JS functions (IIFE's). There's one function for each question and they all look identical to this one:
var question1 = (function() {
var userAnswer1 = prompt(arrayQuestions[0]);
if((userAnswer1.toUpperCase() === "BOSTON") || (userAnswer1.toUpperCase() === "BOS")) {
// inserts correct or incorrect message after user guesses
document.getElementById('question1').innerHTML= arrayAnswerCorrect[0];
// changes color of that message
document.getElementById('question1').style.color = "green";
// inserts image via 'src' attribute
document.getElementById('img1').src = "images/correct.png";
scoreIt++;
} else {
document.getElementById('question1').innerHTML = arrayAnswerIncorrect[0];
document.getElementById('question1').style.color = "red";
document.getElementById('img1').src = "images/incorrect.png";
};
}());
Thank you in advance. This is really stumping me.
Upvotes: 0
Views: 44
Reputation: 19354
The questions and DOM updates are in single block of code that starts, asks questions one at a time, and finally completes execution after the last question.
But javascript threads run to completion: once started nothing interrupts them until the code returns. Prompts just block the javascript thread until the user enters the information. Although browsers accept modifications to the DOM during an execution thread, and may reflect changes to the DOM back in DOM element attributes, they generally defer re-rendering the page until the script has finished.
You will need to rethink how to ask the questions in order but run the code for each question to completion before starting the next one. Two possibilities are obvious: 1) The "next question" button, and 2) looking into using a setTimeout
call to call the next question code. good luck ;-)
Upvotes: 1