Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
I can not seem to get a while loop to work with my code

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);
}

https://jsfiddle.net/e6cbt2dz/

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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 = [#]; <- this needs to hold all the available names

//images for each one
//var bg = [#]; <-this needs to hold all the available images
let keepPlaying = function(){
  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(replay == 'yes')
    keepPlaying()
  else
    return(score)
}()
about 4 years ago · Juan Pablo Isaza Relatório

0

The while loop will not wait for setTimeout() to complete .You need to find out a different way.

This both line are not valid

var pname = [#] // var pname = ['#']
var bg = [#],   // var bg = ['#']

var score = 0
var replay = "yes"
var pname = ['#']
var bg = ['#']

var index = 0;
(function asyncLoop() {
  background = bg[num = Math.floor(Math.random() * bg.length)];
  document.body.style.backgroundImage = 'url(' + background + ')';
  setTimeout(function() {
     var answer = prompt("What pokemon is this?")
     if (answer == pname[num]) {
      alert("correct")
      score ++
      replay = prompt("Want to keep playing?")
    } else {
      alert("incorrect")
      replay = prompt("Want to keep playing?")
    }
    if (replay == 'yes'){
       asyncLoop();
    } 
     
  }, 1000);
})();
<body></body>

about 4 years ago · Juan Pablo Isaza Relatório

0

Let me point out a few things in the code first.

var pname = [#] --> is not a valid syntax

var bg = [#], --> not valid and having a comma here

Also the setTimeOut function is getting executed many times hence making the script unresponsive.

Give this a try :

  • I have excluded the image section from the code, which you can add later and try.

var pname = ['qq','ww','ee'];
   
var replay = "yes";

var score = 0;

var bg = [];

var num = 1;

keepPlaying();

function keepPlaying() {
  
    var answer = prompt("What pokemon is this?")
  
    if (answer == pname[num]) {
        alert("correct")
        score ++
        replay = prompt("Want to keep playing?")
    } 
    else {
        alert("incorrect")
        replay = prompt("Want to keep playing?")
    }
    if(replay == 'yes') {
        keepPlaying();
    }
    else {
        alert(score);
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda