3 回答

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>

TA貢獻1810條經驗 獲得超4個贊
這是一個解決方案,
var x = Math.floor(Math.random() * 5) + 1 ;
& 這是解釋,Math.random() 從 0.000* - 1 生成隨機數 Math.floor() 將該數字四舍五入到最接近的整數如果該隨機數為 1,則整個表達式給出 6 即。max 否則小于但不是 0 bcoz 1 總是添加 希望你能理解 ??

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
添加回答
舉報