2

Basically, i'm doing a website that roll dice for two players where each dices are shown as images.

enter image description here

It works great and show the final dices like it should.

But then i wanted the dices to show some other dices (like 3-5 other faces) before showing the final images as to make some animation.

//put some delay
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

//function that load the new image tag
function imgOnload(obj) {
  var oldImage = document.querySelector("#xDice1");
  oldImage.parentNode.replaceChild(obj, oldImage);
}

function imgOnload2(obj) {
  var oldImage2 = document.querySelector("#xDice2");
  oldImage2.parentNode.replaceChild(obj, oldImage2);

}

//main function called by the button "roll"
function roll() {
  var dice1 = "images/dice" + (Math.floor(Math.random() * 6) + 1) + ".png";
  var dice2 = "images/dice" + (Math.floor(Math.random() * 6) + 1) + ".png";
  //final dices

  var n = 5; //calling the five fake dices
  for (var i = 0; i < n; i++) {
    var imgObj1 = new Image();
    var imgObj2 = new Image();
    //beeing sure that they are all loaded
    imgObj1.onload = function() {
      imgOnload(imgObj1);
    };
    imgObj1.src = "images/dice" + (Math.floor(Math.random() * 6) + 1) + ".png";
    imgObj1.id = "xDice1";

    imgObj2.onload = function() {
      imgOnload2(imgObj2);
    };
    imgObj2.src = "images/dice" + (Math.floor(Math.random() * 6) + 1) + ".png";
    imgObj2.id = "xDice2";

    //putting some delay
    sleep(2000);
  }
  
  //showing the final dices
  document.querySelector("#xDice1").setAttribute("src", dice1);
  document.querySelector("#xDice2").setAttribute("src", dice2);

}

On the paper, it should work... but for some reason the images only finish to charge in the end of the script so only the last dices are shown on the screen. Even when i put some delay to let the images charge between each iteration, it just wait longer from the empty dices of the start to the final dices.

enter image description here

Can anyone help me about this? It is my first time putting a question so if some info are missing i will update it as soon as possible!

Thx

wazz
  • 4,953
  • 5
  • 20
  • 34
Laoshi
  • 21
  • 1
  • Your `sleep` method locks the browser during the whole time it executes, so the browser can't update the rendering. – Kaiido Sep 16 '21 at 09:04

0 Answers0