War Project – Set Timeout

We’re missing the most exciting part of the game, the tie. I decided to start with the looks first. If the card we put down is a tie, then we put down three more cards. That’s what’s going to happen today. Then we’ll get to putting down a fourth card and seeing who wins.

else if (number2 > number1){

//checks if player two wins the round

\$winner.html(“Player Two Wins”);

//announces that player two wins

for (i=0; i<playedCards.length; i++) {

secondPlayer.push(playedCards[i]);

//player two gets the cards

}

} else if (number1 == number2) {

//checks if the players tied

\$winner.html(“This means war!”);

//announces the war

for (i=0; i<3; i++){

//loops three times for three cards

playedCards.push(firstPlayer[0]);

//one card from each player’s hand is played

playedCards.push(secondPlayer[0]);

//they go into the played cards array

firstPlayer.splice(0,1);

//they are taken off the players’ arrays

secondPlayer.splice(0,1);

}

\$firstPlayerSuit.css(“display”, “none”);

//removes the suit from the card area

\$secondPlayerSuit.css(“display”, “none”);

//removes the suit from the card area

numberImg1 = “<img style=’height:14rem;’ src=’./images/cards.png’/>”;

\$firstPlayerNumber.html(numberImg1);

//places an image in the number area of a card back

numberImg2 = “<img style=’height:14rem;’ src=’./images/cards.png’/>”;

\$secondPlayerNumber.html(numberImg2);

//places an image in the number area of a card back

var audio = new Audio(‘card.mp3’);

//creates a variable that holds the sound of a card

audio.play();

//plays the sound

window.setTimeout(function() {

//delays the next thing from happening for 1000ms

audio.play();

//plays audio

}, 1000);

//determines how long to wait

window.setTimeout(function() {

//same thing again

audio.play();

}, 1800);

//this time waits 1800ms to separate the sounds

}

The setTimeout function delays something from happening. Otherwise, the code just runs in order top to bottom, but goes so quickly that it seems instantaneous. It doesn’t listen for the one to play and then play the other. It just hits play three times in a row very, very, quickly. The three audio sounds seem like they are just one sound. Delaying the start of the second and third sound gives the sound of three cards being put down.

You can watch this lesson.