title: Use While Loop With setTimeout
body: <p>I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:</p>
  
  <pre><code>function battle(enemy) {
  var battleOver = false;
  console.log(enemy.name + " appears!");
  //problem loop here.
  while(battleOver === false){
  console.log("This enemy has " + enemy.health + " health.");
  for (var i = 0; i &lt; userWeapons.length; i++) {
      var ibumped = i + 1;
      console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
  }
  var weaponChosen;
  setTimeout(function() {
      var weaponChoice = prompt("Which weapon do you choose?");
      switch (weaponChoice) {
          case 1:
              weaponChosen = userWeapons[0];
              console.log(userWeapons[0].name + " chosen.");
              break;
          case 2:
              weaponChosen = userWeapons[1];
              console.log(userWeapons[1].name + " chosen.");
              break;
          default:
              weaponChosen = userWeapons[0];
              console.log(userWeapons[0].name + " chosen.");
  
      };
  }, 1000);
  setTimeout(function() {
      if (enemy.shields &gt; 0 &amp;&amp; weaponChosen.ignoreShield === false) {
          enemy.shields = enemy.shields - weaponChosen.damage;
          weaponChosen.fire(enemy);
          if (enemy.shields &lt; 0) {
              enemy.health = enemy.health + enemy.shields;
              console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
          } else {
              console.log("Enemy shields have been reduced to " + enemy.shields + ".");
          }
      } else {
          enemy.health = enemy.health - weaponChosen.damage;
          weaponChosen.fire(enemy);
          console.log("Enemy takes " + weaponChosen.damage + " damage!");
      }
      if (enemy.health &lt;= 0 &amp;&amp; battleOver === false) {
          console.log("Enemy destroyed!");
          battleOver = true;
      }
  }, 3000);
  setTimeout(function() {
      if (enemy.health &gt; 0 &amp;&amp; battleOver === false) {
          if (enemy.weapons != null) {
              console.log(enemy.weapons.name + " fired at you.");
              health = health - enemy.weapons.damage;
              console.log("You have " + health + " health left.");
              if (health &lt;= 0) {
                  console.log("Game over... You were destroyed");
                  battleOver = true;
              }
          } else {
              console.log("The enemy did nothing...");
          }
      };
  }, 5000);
  }
  }
  </code></pre>
  
  <p>All help is appreciated!</p>