我试图通过结合do while循环和setInterval函数来模拟骰子滚动。
目标是:用户点击骰子滚动按钮。他们查看一系列数字,然后滚动停止并返回一个值。
我的想法是使用'do while'循环来控制在骰子停止'滚动'之前发生了多少次迭代。我尝试了一些不同的东西,但到目前为止还没有任何工作。我的最新尝试如下。
function diceRoll(){
theNum = Math.floor(Math.random() * 6) + 1;
counter = counter + 1;
console.log(theNum);
console.log(counter);
}
$(document).ready(function(){
counter = 1;
myVar = '';
$('#start').click(function(){
do {
//
myVar = setInterval(function(){ diceRoll() }, 500);
} while (counter < 10)
});
答案 0 :(得分:3)
忘记do while
循环。你只需要跟踪状态&#39;所以你可以在每个间隔做出相应的行动。在这个简单的情况下,counter
会很好。
如果使用间隔,则需要在完成间隔后清除间隔。阻止&#39;阻塞&#39;滚动骰子时的开始按钮。
以下是您的代码的修改示例,它应该实现您要执行的操作:
var vals = ["\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"];
function setValue(num) {
$("div").text(vals[num - 1]);
}
var intervalId;
var counter = 1;
function diceRoll() {
theNum = Math.floor(Math.random() * 6) + 1;
counter = counter + 1;
setValue(theNum);
}
$(document).ready(function() {
$('#start').click(function() {
if (intervalId)
return; // Don't allow click if already running.
intervalId = setInterval(function() {
if (counter < 10)
diceRoll();
else {
// Reset state ready for next time.
clearInterval(intervalId);
intervalId = null;
counter = 1;
}
}, 500);
});
});
&#13;
div {
font-size: 100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="start">Click to Roll</a>
<div>
</div>
&#13;
答案 1 :(得分:1)
setInterval
会立即返回,因此您的所有代码都在进行大量的迭代(counter
变量在许多版本执行之前不会递增)
您应该在函数本身内使用setTimeout
重新调用相同的函数。
var counter = 0;
function diceRoll(){
theNum = Math.floor(Math.random() * 6) + 1;
counter = counter + 1;
console.log(theNum);
console.log(counter);
if(counter<10){
setTimeout(diceRoll,500);
}
}
diceRoll()
答案 2 :(得分:1)
您不需要do while
。您可以自己处理索引。 fiddle
function diceRoll() {
theNum = Math.floor(Math.random() * 6) + 1;
console.log(theNum);
}
$(document).ready(function() {
var counter = 1;
var interval = setInterval(function() {
if (counter < 10) {
diceRoll()
counter = counter + 1;
} else {
clearInterval(interval);
}
}, 500);
});
答案 3 :(得分:1)
您的示例中有两个问题,
第一个问题是,setInterval会在某些函数后继续执行给定的函数,你不需要为了类似的目的而执行do while循环。
第二个问题是,不是使用setInterval来保持执行并检查计数器是否&lt; 10到clearInterval,你可以使用setTimeout来创建另一个超时,当计数器&lt; 10并调用diceRoll函数本身。
var counter,
timeout;
function diceRoll(){
theNum = Math.floor(Math.random() * 6) + 1;
counter = counter + 1;
console.log(theNum);
console.log(counter);
if (counter < 10) {
timeout = setTimeout(diceRoll, 500);
}
}
$(document).ready(function(){
$('#start').click(function(){
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
counter = 0;
diceRoll();
});
}