I would like to add a small dice rolling effect to my Javascript code. I think a good ways is to use the setInterval() method. My idea was following code (just
Like callbacks you can use Promises to pass a function that is called when the program is done running, if you use reject you can also handle errors with Promises.
function rollDice() {
return new Promise((resolve, reject) => {
const dice = document.getElementById("dice")
let i = Math.floor((Math.random() * 25) + 5)
const intervalId = setInterval(() => {
const diceValue = Math.floor((Math.random() * 6) + 1)
dice.src = `./images/dice/dice${diceValue}.png`
if (--i < 1) {
clearInterval(intervalId)
resolve(diceValue)
}
}, 50)
})
}
Then use it like this:
rollDice().then(value => alert(`Dice rolled: ${value}`))