在while循环中正确执行setInterval

Executing setInterval correctly within a while loop

我正在尝试 运行 while 循环中的 setInterval 过程,该过程生成随机骰子数并设置骰子图形以反映这一点。我打算使用 setInterval 在每个 while 循环迭代之间添加延迟,以便 UI 代表骰子 "rolling",而不是仅仅返回最终值。

就目前而言,无论 if 语句中的条件如何,setInterval 都不会停止。理想情况下,这将是 'num' 本身,以便可以在其他地方定义掷骰子的数量。

//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++;
    };
};

非常感谢大家

这是一个方法,它会掷骰子指定的次数并在下一次掷骰之前等待 500 毫秒。我认为这应该对您有所帮助。

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

我对代码片段进行了一些更改,因此它不会在不再需要时安排新的抛出。