Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
1.5: High Card setTimeout

Introduction

Add setTimeout to High Card to add a delay when the user clicks the deal button. We will also want a global boolean variable canClick that represents whether the user has recently clicked and we are waiting for the delay to end. If we didn't have canClick, the user could trigger multiple setTimeouts.

Code Samples

Globals

1
let canClick = true;
2
let cardContainer;
Copied!

Game Initialisation

1
const initGame = () => {
2
// other game init code goes here
3
// ...
4
cardContainer = document.createElement('div');
5
document.body.appendChild(cardContainer);
6
};
Copied!

Helper Functions

1
// other helper functions
2
// ...
3
const createCard = (card) => {
4
const cardEl = document.createElement('p');
5
cardEl.innerText = card.name; // also output the other attributes
6
return cardEl;
7
};
Copied!

Player Click Callbacks

1
const player1Click = () => {
2
if (playersTurn === 1 && canClick === true) {
3
canClick = false;
4
​
5
setTimeout(() => {
6
player1Card = deck.pop();
7
​
8
const cardElement = createCard(player1Card);
9
​
10
// in case this is not the 1st time
11
// in the entire app,
12
// empty the card container
13
cardContainer.innerHTML = '';
14
​
15
cardContainer.appendChild(cardElement);
16
playersTurn = 2;
17
canClick = true;
18
}, 2000);
19
}
20
};
21
​
22
const player2Click = () => {
23
if (playersTurn === 2 && canClick === true) {
24
canClick = false;
25
​
26
setTimeout(() => {
27
const player2Card = deck.pop();
28
const cardElement = createCard(player2Card);
29
​
30
cardContainer.appendChild(cardElement);
31
​
32
playersTurn = 1;
33
canClick = true;
34
​
35
if (player1Card.rank > player2Card.rank) {
36
output('player 1 wins');
37
} else if (player1Card.rank < player2Card.rank) {
38
output('player 2 wins');
39
} else {
40
output('tie');
41
}
42
}, 2000);
43
}
44
};
Copied!

Exercise

Add setTimeout to your High Card game.
Last modified 2mo ago