0

I am trying to run a setInterval process within a while loop that generates a random dice number and sets the dice graphic to reflect this. I'm intending to use the setInterval to add a delay between each while loop iteration so that the UI represents the dice "rolling", rather than just returning the final value.

As it currently stands, the setInterval does not stop regardless of the condition placed within the if statement. Ideally, this would be 'num' itself, so that the number of dice rolls can be defined elsewhere.

//roll dice num times
function rollDice(num) {
    var counter = 0;
    var i = 0;
    while (i < num){
        var diceDOM2 =  document.querySelector(".dice");

        var diceIntervalID = setInterval(function(){

            //1. Rnd number
            dice2 = Math.floor(Math.random()* 6) + 1;

            // 2. Update diceDOM with new dice value
            diceDOM2.style.display = "block";
            diceDOM2.src = "dice-" + dice2 + ".png";
            console.log(diceDOM2.src);

            //determine setInterval exit
            counter++;
            console.log(counter);
            if(counter > num){
                clearInterval(diceIntervalID);

            }
        }, 1500);
        i++;
    };
};

Many thanks all

3
  • setInterval and loops of any kinda are usually a really bad idea. what exactly are you trying to accomplish? Commented Aug 27, 2017 at 19:53
  • So, you want the dice to keep rolling for n times, with an interval of 1.5s between each roll? Commented Aug 27, 2017 at 20:01
  • @rossipedia, it's as Manuel Otto assumed below. I forgot to reduce the interval delay down from 1500ms for this post - I only put it that high so I could watch the console logging more clearly. Commented Aug 27, 2017 at 22:28

1 Answer 1

3

Here is a method that will roll the dice the specified number of times and waits 500ms before the next roll. I think this should help you along.

function rollDice(numberOfRolls) {      
  console.log(`rolling the dice`);
  var diceThrow = Math.floor((Math.random() * 6) + 1);

  console.log(`The dice reads ${diceThrow}`);
  // Lower the number of rolls left.
  numberOfRolls--;

  // Check if there is a throw left...
  if (numberOfRolls < 1) {
    console.log('The dice have been rolled the requested number of times.');
    // No more throws left, exit the method without scheduling a new throw.
    return;
  }

  // Set a timeout of 500ms after which to throw the dice again.
  console.log('Waiting 500ms till the next throw');
  setTimeout(() => {
    // Call the rollDice method with the lowered number of throws.
    rollDice(numberOfRolls);
  }, 500);
  
}

// Roll the dice 3 times
rollDice(3);

I've made some changed to the snippet so it doesn't schedule a new throw when it is no longer needed.

Sign up to request clarification or add additional context in comments.

4 Comments

that's great, thanks! Looks like staying away from setInterval within the loop is a better move, as @rossipedia mentioned above!
If I have a further question about the implementation of this solution, where would I post that?
Here? I'm not sure what is the StackOveflow way of doing this. Or you could create a new question and place the link here. I will have a look when I can.
Were you able to solve your problem. If you're happy with this answer, can you mark it as the excepted answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.