Search code examples
javascriptjquerysynchronizationjquery-click-event

Inside a click event handler I have 3 functions. Why is the 3rd function executing before the first two are finished?


I am writing a tic-tac-toe game in javascript. When a square on the board is clicked three functions are called in the following order.

  1. move() -this function displays the players character (X or O) in the clicked square.
  2. computer() - this function determines the best square to select and then displays the computer's character (X or O) in the chosen square.
  3. gameOver() - this function checks to see if either player1 or player2 have won the game. If the game has been won a message is alerted declaring the winner and the board is cleared.

    $(".num").on("click", function(){
      var square = $(this).attr("id");
    
      //Display users' moves, push moves into the correct user's moves 
      //array, remove the chosen square from the open array, and increment 
      //the count.
      move(square);
    
      //If the user has chosen to play the computer and the board is not 
      //full, execute the computer's move.
      if(twoPlayers===false && count<9){
        computer();
      }
    
      //Check for a win or draw.
      gameOver();
    })
    

    Why is it that once a game has been won, the board is cleared before the winning moves are displayed??

Here is a link to the codepen


Solution

  • It's not being cleared before the winning moves are displayed. It just happens so fast that you can't see the last move. Wrap your gameOver() call in a setTimeout to give it enough time to see the move displayed like so:

    $(".num").on("click", function(){
        var square = $(this).attr("id");
    
        //Display users' moves, push the user's moves into the correct moves array, remove the chosen square from the open array, and increment the count.
        move(square);
    
        //If the user has chosen to play the computer and the board is not full, execute the computer's move.
        if(twoPlayers===false && count<9){
            computer();
        }
    
        //Check for a win or draw.
        setTimeout(gameOver, 3000);
    })
    

    Here is a like to an updated codepen

    I haven't gone all the way through your source to see where you update the display. However, I have made a new codepen with alert's at the end of each function. You can clearly see each function executing in order even on the last move. The game over function clears the board and you will see that the last move is not displayed.