使用 JS 和 setTimeout 掷骰子

我正在尝试使用该setTimeout函数创建一个rollthedice函数,但我有 10 个数字而不是 6 个。


<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Roll Dice</title>


<style>


button {

    padding: 16px 24px;

}


</style>


</head>

<body>


    <button class="roller" onclick="rollTheDice()">Roll</button>

    <h2 class="number">0</h2>

    

</body>


<script>


    function rollTheDice() {

        var x = Math.floor(Math.random()*10)

        document.querySelector(".number").innerHTML = x; 

        setTimeout(rollTheDice, 1000); 

    }


   

</script>


</html>

这进入了无限循环。



繁花如伊
浏览 127回答 3
3回答

慕娘9325324

添加一个counter变量以预先确定在轮子停止之前将显示多少个数字:<button class="roller" onclick="counter=20;rollTheDice()">Roll</button>然后减少并且仅在大于 0时才counter调用。setTimeoutcounterif (--counter>0) setTimeout(rollTheDice, 100);<html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Roll Dice</title><style>button {&nbsp; &nbsp; padding: 16px 24px;}</style></head><body>&nbsp; &nbsp; <button class="roller" onclick="counter=20;rollTheDice()">Roll</button>&nbsp; &nbsp; <h2 class="number">0</h2>&nbsp; &nbsp;&nbsp;</body><script>&nbsp; &nbsp; function rollTheDice() {&nbsp; &nbsp; &nbsp; &nbsp; var x = Math.floor(Math.random()*10)&nbsp; &nbsp; &nbsp; &nbsp; document.querySelector(".number").innerHTML = x;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (--counter>0) setTimeout(rollTheDice, 100);&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;</script></html>

慕莱坞森

这是一个解决方案,var&nbsp;x&nbsp;=&nbsp;Math.floor(Math.random()&nbsp;*&nbsp;5)&nbsp;+&nbsp;1&nbsp;;& 这是解释,Math.random() 从 0.000* - 1 生成随机数 Math.floor() 将该数字四舍五入到最接近的整数如果该随机数为 1,则整个表达式给出 6 即。max 否则小于但不是 0 bcoz 1 总是添加 希望你能理解 😀

波斯汪

你需要告诉它在 10 次后停止。所以我会计算它运行的次数并设置一个目标数量,并且只有在它没有达到该目标数量时才重置超时。function loop(i){&nbsp; &nbsp; let rolls = 0;&nbsp; rollTheDice()&nbsp;&nbsp;&nbsp; function rollTheDice() {&nbsp; &nbsp; var x = Math.floor(Math.random()*10)&nbsp; &nbsp; document.querySelector(".number").innerHTML = x;&nbsp;&nbsp; &nbsp; rolls++;&nbsp; &nbsp; if(rolls < i) {&nbsp; &nbsp; &nbsp; setTimeout(rollTheDice, 300);&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp; }}&nbsp; &nbsp;&nbsp;loop(10) // set the target rolls
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript