I am trying to get a function to repeat the code of a seperate eventListener. The event listener merely performs the proces once. The while loop intends to complete the process 'num' times. Whilst the eventListener button works, and will assign the "dice-" + dice + ".png" correctly and display the appropriate graphic file, the the while loop does not. It generates a random .png file, and displays this num times, even whilst each iteration does produce a new random number. I have named the variables for each case seperately to avoid confusion.
document.querySelector(".btn-roll").addEventListener("click", function(){
//1. Rnd number
dice = Math.floor(Math.random()* 6) + 1;
//2. Display the result
var diceDOM = document.querySelector(".dice");
diceDOM.style.display = "block";
diceDOM.src = "dice-" + dice + ".png";
console.log(diceDOM);
});
//roll dice num times
function rollDice(num) {
var i = 1;
var dice2 = 0;
while ( i < num){
//1. Rnd number
dice2 = Math.floor(Math.random()* 6) + 1;
console.log("Dice: " + dice2); //error checking. dice2 is producing new number each loop iteration
//update diceDOM with new dice value
var diceDOM2 = document.querySelector(".dice");
diceDOM2.style.display = "block";
diceDOM2.src = "dice-" + dice2 + ".png";
console.log(diceDOM2); //error checking. diceDOM appears to be set on calling loop fist time (not set by dice var, but an alternative random number)
i++;
};
};
Aucun commentaire:
Enregistrer un commentaire