亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號