一键调用setInterval和ClearInterval

一键调用setInterval和ClearInterval

我试图让数字1-6在单击按钮时快速在屏幕上闪烁,然后停止并显示随机生成的数字。如果将clearInterval放入函数中,它将仅显示随机数,而不会在显示之前显示闪烁的数字。

的HTML

<div id='dice'>
    <div id='number'>0</div>
</div>
<div id='button'>
    <button onclick='roll()'>Roll Dice</button>
</div>


JAVASCRIPT

let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  let shuffleDice = setTimeout(function(){
    diceNumber.innerHTML = diceSides[i++];
    if(diceNumber == diceSides.length){
      i = 0;
    }
  }, 500);

  let random = Math.floor(Math.random() * 6);
    diceNumber.innerHTML = random;
}

最佳答案

也许这对你有用
提示:您可以将i用作计数器变量,也可以使用您的方法(用数字定义数组,并使用索引查找它们并将它们放在number标记中)

HTML:

<div id='dice'>
    <div id='number'>0</div>
</div>
<div id='button'>
    <button onclick='roll()'>Roll Dice</button>
</div>


JS:

let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
    diceSides = [1,2,3,4,5,6];
    var i = 6;
    let shuffleDice = setInterval(function(){
        diceNumber.innerHTML = i;
        if(i == 0){
            clearInterval(shuffleDice);
            let random = Math.floor(Math.random() * 6);
            diceNumber.innerHTML = random;
        }
        i--;
    }, 1000);
}


CodePen
clearInterval
setInterval
setTimeout

关于javascript - Javascript:一键调用setInterval和ClearInterval?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47684375/

10-12 07:02