When I put the while loop in like this, my background and my prompts never show up. I have no clue on why would be causing this. Everything else works to perfection, it is just once I add the while loop my code breaks. I have tried a for loop as well but it also does not work.
//score
var score = 0
//replay loop
var replay = "yes"
//name of each gen 1 pokemon
var pname = [#]
//images for each one
var bg = [#],
while (replay == 'yes'){
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' background ')';
setTimeout(() => {
var answer = prompt("What pokemon is this?")
if (answer.toLowerCase == pname[num].toLowerCase) {
alert("correct")
score
replay = prompt("Want to keep playing?")
} else {
alert("incorrect")
replay = prompt("Want to keep playing?")
}
}, 2000);
}
CodePudding user response:
setTimeout function is going to take 2 seconds before it runs, thus causing your while loop to execute an actual massive number of times in 2 seconds... all the time updating the background image (which it probably does easily over 10,000 X in 2 seconds.
I suggest using recursion:
//score
var score = 0;
//replay loop
var replay = "yes";
//name of each gen 1 pokemon
var pname = [];
//images for each one
var bg = [];
let keepPlaying = () =>{
background = bg[Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' background ')';
var answer = prompt("What pokemon is this?")
if (answer.toLowerCase == pname[num].toLowerCase) {
alert("correct")
score
replay = prompt("Want to keep playing?")
} else {
alert("incorrect")
replay = prompt("Want to keep playing?")
}
if(reply == 'yes')
keepPlaying()
else
return(score)
}()
CodePudding user response:
The while loop will not wait for setTimeout().You need to find out a different way.
This both line are not valid
var pname = [#] // var pname = ['#']
var bg = [#], // var bg = ['#']