EDIT: While this question has been answered and very well, I wanted to share another answer I found that I think explains the issue more in depth just for the sake of learning: Javascript - Are DOM redraw methods synchronous?
Rock Paper Scissors Github Project
The issue: I am writing a program Rock Paper Scissors for The Odin Project. This calls a function updateElements() to change the textContent of on page variables to display the round statistics. This functions works properly until the win condition is met in the function roundCounter(); however, roundCounter() should not be called before the function updateElements() completes.
updateElements() -> roundCounter() -> globalReset()
A win or loss condition is met when any of the round counting variables reaches 3. This can result in a win, draw, or loss. In any condition being met a prompt occurs which asks the player to either begin a new game or not. This is my error, it seems that the win condition is somehow met prior to updateElements() being able to finish updating the DOM.
Console logs left from when it was console only, show that the variables are on the correct iteration. One possible solution that my mentor and I worked on was causing a timeOut to occur prior to roundCounter() being called. This does work if set to anything greater than 20ms. Yes this is a solution. I am here asking for more understanding on what and why this issue is happening. Why does the DOM not draw the new values before the next function? Why does the prompt stop the DOM from updating? Any help would be much appreciated!
function updateElements() {
let pScore = `${playerWins}`;
let cScore = `${computerWins}`;
let dCount = `${nobodyWins}`;
let rCount = `${roundCount}`;
PLAYER_SCORE.textContent = pScore
COMPUTER_SCORE.textContent = cScore;
DRAW_COUNT.textContent = dCount;
ROUND_COUNT.textContent = rCount;
roundCounter();
}
Which then moves to roundCounter()
function roundCounter() {
console.log(`Your wins: ${playerWins} \nComputer Wins: ${computerWins} \nDraws: ${nobodyWins} \nRound Count: ${roundCount}`);
if (roundCount === 5 && computerWins < 3 && playerWins < 3 && nobodyWins < 3 ) {
console.log("This game was a draw");
newGamePrompt();
} else if (roundCount <= 5) {
if (playerWins === 3) {
console.log("You are the winner!");
newGamePrompt();
} else if (computerWins === 3) {
console.log("You lose!");
newGamePrompt();
} else if (nobodyWins === 3) {
console.log("Nobody won!");
newGamePrompt();
}
} else if (roundCount > 5) {
console.log(
"An error has occured: The game has run too many rounds. Restarting");
newGameYes();
}
}
Prompt displays before DOM updates
Canceling the Prompt causes DOM to finish updating
Troubleshooting Steps taken:
Removing the newGamePrompt(), setting playAgain locally to "no"
- no change.
Debugger:
- Counter updates appropriately.
- Executes in appropriate order.
console logging:
- updateElements() and roundCounter() show the correct value.