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...');

In this example, the DiceGame class has a public method called playTurn that simulates a player's turn in the dice game. The playTurn method uses setTimeout to delay the execution of the rollDice method by 1 second (1000 milliseconds).

While the playTurn method is waiting for the timer to expire, the rest of the code continues to run. This is why the console.log statement outside of the playTurn method is executed before the dice is rolled.

Once the timer expires, the rollDice method is executed, and the current roll is logged to the console. The playTurn method then completes, and the turn is over.

Using setTimeout in this way allows us to add a delay to the dice roll, which can make the game feel more realistic and interactive.

Last updated