在while循环中正确执行setInterval

时间:2017-08-27 19:50:47

标签: javascript while-loop setinterval clearinterval

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

就目前情况而言,无论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++;
    };
};

非常感谢所有人

1 个答案:

答案 0 :(得分:2)

这是一种方法,它将掷骰子指定的次数,并在下一次掷骰前等待500ms。我认为这应该可以帮助你。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

我已经对片段进行了一些更改,因此在不再需要时不会安排新的投掷。