Dice game example
Here is an example of using setTimeout in the context of a dice game:
class DiceGame {
// Public field
currentRoll = null;
rollDice() {
// Generate a random number between 1 and 6
this.currentRoll = Math.floor(Math.random() * 6) + 1;
console.log(`You rolled a ${this.currentRoll}`);
}
// Public method
async playTurn() {
console.log('Rolling dice...');
// Wait 1 second before rolling the dice
await new Promise(resolve => setTimeout(resolve, 1000));
this.rollDice();
console.log('Turn over');
}
}
const game = new DiceGame();
// This function call is asynchronous
game.playTurn();
console.log('Waiting for turn to end...');Last updated