Basically, i'm doing a website that roll dice for two players where each dices are shown as images.
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.
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