Tic Tac Toe - Order of events

Tic Tac Toe - Order of events
0.0 0

#1

Hi campers,

maybe someone can help me out with the order of events in my tic tac toe game. My problem: The evaluation of the game takes place before the X or O is set in the field. I tried to register a 2nd click-event handler to make things right. They seem to be called in the right sequence:

  1. function turnPlayed, which should set the X or O
  2. the anonymous .click function, which evaluates the game state

In the console.log, you can see that the order is ok. However, the win/lose alert comes before the symbol is set. I hope, this does not sound as confused as I feel right now. However, it should become clear, if you try to lose a game:

Thanks in advance for your help!


#2
setTimeout(function(){
    alert("Congratulations! You won!");
}, 10);

Something like this?


#3

Hi,
thanks for the answer and sorry for the late reply!
The timeout seems to do the trick. However, I still don’t quite get why the evaluation is not performed before the alert. I’d have expected this kind of behavior if it was an AJAX-call (twitch-challenge… oh the pain…). But here, the methods should be executed sequentially, shouldn’t they?
Maybe I should revisit the Javascript basics. I took a pretty lengthy Free Code Camp break.


#4

The following Stack Overflow post’s accepted answer explains why this happens.


#5

Yes! Thank you! Both of you!