TopTomato TopTomato - 1 year ago 82
Javascript Question

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.

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’. 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;

counter = 1;
myVar = '';
do {
myVar = setInterval(function(){ diceRoll() }, 500);
} while (counter < 10)

Answer Source

Forget the do while loop. 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.

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 = ["\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;

$(document).ready(function() {

  $('#start').click(function() {
    if (intervalId)
      return; // Don't allow click if already running.

    intervalId = setInterval(function() {
      if (counter < 10)
      else {
        // Reset state ready for next time.
        intervalId = null;
        counter = 1;
    }, 500);
div {
  font-size: 100px;
<script src=""></script>
<a id="start">Click to Roll</a>