简体   繁体   English

如何结合do while循环和setInterval计时器功能

[英]how to combine a do while loop and setInterval timer function

I am trying to simulate a dice roll by combining a do while loop and a setInterval function. 我正在尝试通过组合do while循环和setInterval函数来模拟掷骰子。

the goal is this: user clicks dice roll button. 目标是:用户单击掷骰子按钮。 they view a series of numbers and then the roll stops and returns a value. 他们查看一系列数字,然后滚动停止并返回一个值。

my idea was to use the 'do while' loop to control how many iterations occur before the dice stops 'rolling'. 我的想法是使用“ do while”循环来控制骰子停止“滚动”之前发生了多少次迭代。 i've tried a few different things but nothing has worked so far. 我尝试了几种不同的方法,但到目前为止没有任何效果。 my latest attempt is below. 我的最新尝试如下。

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)
    });

Forget the do while loop. 忘记do while循环。 You just need to keep track of 'state' so you can act accordingly at each interval. 您只需要跟踪“状态”,就可以在每个时间间隔内采取相应的行动。 The counter will do fine in this simple case. 在这种简单情况下, counter会很好用。

If using an interval you want to clear the interval when you have finished with it. 如果使用间隔,请在完成间隔后清除间隔。 It would also make sense to 'block' the start button while the dice in rolling. 当骰子滚动时,“阻塞”开始按钮也很有意义。

Here is a modified example of your code which should achieve what you are trying to do: 这是代码的修改示例,应该可以实现您要执行的操作:

 var vals = ["\⚀", "\⚁", "\⚂", "\⚃", "\⚄", "\⚅"]; 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); }); }); 
 div { font-size: 100px; } 
 <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> 

setInterval returns immediately, so all your code is doing is kicking off a very large number of iterations (the counter variable will not be incremented before many many versions are executing) setInterval立即返回,因此您的所有代码正在启动大量的迭代(在执行许多版本之前, counter变量不会递增)

You should just recall the same function with setTimeout from within the function itself. 您应该只从函数本身内部使用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() 

You don't need the do while . do while You can just handle the indexing yourself. 您可以自己处理索引。 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);

});

Two problems in your example, 您的示例中有两个问题,

The first problem is, setInterval will keep execute the given function after certain function, you don't need a do while loop for similar purpose. 第一个问题是,setInterval将在某些函数执行完后继续执行给定的函数,出于类似的目的,您不需要执行while循环。

The second problem is, instead of using setInterval to keep execute and check whether counter < 10 to clearInterval, you may use setTimeout instead, to create another timeout when counter < 10 and call the diceRoll function itself. 第二个问题是,不是使用setInterval保持执行并检查counter <10是否为clearInterval,而是可以使用setTimeout在计数器<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();
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM