As I was building my javascript Tic Tac Toe game, I ran into a problem where the game board elements wouldn’t update before the game declares a winner or when it’s a draw.

TTT1 TTT2

Here is my javascript code that is handling the declaration of a winner

if (win) {
    alert("Player " + player + " wins!");
    resetBoard();
  } else if
.
.
.

Turns out other people have similar issues on stackoverflow:

I think the best explanation (in plain english) for why this is happening is that

when code makes a rapid sequence of DOM or style changes, the browser does not attempt to update the view between each one. Instead, it waits for things to calm down and then repaints. - said Pointy

The suggested solution is to use setTimeout() to delay the js code, giving the DOM a chance to update. It’s important to note that

setTimeout() doesn’t pause execution, it merely queues a function to be called at some future point. So, essentially, nothing will happen for 500ms, and then all of your updates will happen at once (technically sequentially, of course). - said Alnitak

Thus, this is what I changed:

if (win) {
    setTimeout(function() {
      alert("Player " + player + " wins!");
      resetBoard();
    }, 100);
  } else if
.
.
.

This worked perfectly! Now the DOM updates before the alert is generated!

TTT3

Here is the full game, have fun!:

See the Pen Tic Tac Toe by Aaron Young (@aaronyoung) on CodePen.