Skip to content
Advertisement

JS die roll simulation with 6 die images

in Js, I want to try to simulate a die roll by showing images of die 1 to 6, but when I try to display these in a for loop, it only displays image dice6. I tried putting in a nested for loop to slow down the outer loop but that didnt work. Does the page need to refresh after changing “src” attribute?

const dieImage = function (num) {
      return "images/dice" + String(num).trim() + ".png";
    };

function dieRoll(num) {
        
          for (let i = 1; i < 7; i++) {
            for (let z = 0; z < 44444; z++) {} // attempt to slow
        
            if (num === 1) {
              img1.setAttribute("src", dieImage(i));
            } else {
              img2.setAttribute("src", dieImage(i));
            }
          }
        }

Advertisement

Answer

As mentioned in the comments you can use setTimeout. You can introduce a delay and give the browser a chance to redraw by using setTimeout, promise, and await, for example like this:

const DELAY = 300; // 300ms

async function dieRoll(num) {
  for (let i = 1; i < 7; i++) {
    if (num === 1) {
      img1.setAttribute("src", dieImage(i));
    } else {
      img2.setAttribute("src", dieImage(i));
    }

    await new Promise((resolve) => setTimeout(() => resolve(), DELAY));
  }
}

The loop execution will stop until the promise is resolved, but it will let the browser to continue to respond and redraw. When the promise is resolved after the timeout callback is run after the given DELAY milliseconds, the next iteration of the loop will take place.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement