为了账号安全,请及时绑定邮箱和手机立即绑定

使用 JS 和 setTimeout 掷骰子

使用 JS 和 setTimeout 掷骰子

繁花如伊 2023-05-19 16:59:25
我正在尝试使用该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>这进入了无限循环。
查看完整描述

3 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

添加一个counter变量以预先确定在轮子停止之前将显示多少个数字:


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

然后减少并且仅在大于 0时才counter调用。setTimeoutcounter


if (--counter>0) setTimeout(rollTheDice, 100);

<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="counter=20;rollTheDice()">Roll</button>

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

    

</body>


<script>


    function rollTheDice() {

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

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

        if (--counter>0) setTimeout(rollTheDice, 100); 

    }


   

</script>


</html>


查看完整回答
反对 回复 2023-05-19
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

这是一个解决方案,

var x = Math.floor(Math.random() * 5) + 1 ;

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


查看完整回答
反对 回复 2023-05-19
?
波斯汪

TA贡献1811条经验 获得超4个赞

你需要告诉它在 10 次后停止。所以我会计算它运行的次数并设置一个目标数量,并且只有在它没有达到该目标数量时才重置超时。


function loop(i){

    let rolls = 0;

  rollTheDice()

  

  function rollTheDice() {

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

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

    rolls++;

    if(rolls < i) {

      setTimeout(rollTheDice, 300); 

    } 

  }

}

    

loop(10) // set the target rolls


查看完整回答
反对 回复 2023-05-19
  • 3 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信