I am attempting to simulate the roll of two six sided dice and show the dice rolling on screen by switching image sources. I intend for the dice to continue rolling until there is no tie. The problem is that the while loop is always true and loops infinitely because the states do not change until after slowRoll is executed. Can this be done with promises or what is the best way to achieve this?
const [topRoll, setTopRoll] = useState(7);
const [botRoll, setBotRoll] = useState(7);
const rollDiceSix = () => {
setTopRoll(Math.floor(Math.random() * 6) + 1);
setBotRoll(Math.floor(Math.random() * 6) + 1);
};
const slowRoll = async () => {
await new Promise((resolve) => {
setTimeout(function () {
resolve(rollDiceSix());
}, 250);
});
while (topRoll === botRoll) {
rollDiceSix();
}
};