Search code examples
javascripthtmlloopsprompt

How to get out of an infinite prompt loop when the prompt is assigned to a variable


Here's my code

function cc() {
  prompt("Choose Character") 
}

function cs() {
 var chars = setTimeout(function(){ cc() }, 3000);
  switch (chars) {
    case "spy":
    selectedspy()
    break;
    case "bulovian soldier":
    selectedbulovian()
    break;
    case "stonian soldier":
    selectedstonian()
    break;
    default:
    cs()
  }
}

it keeps getting stuck in an infinite loop of asking the prompt again. I feel like I'm making a simple mistake, but I couldn't figure what I needed to type into google to get the answer


Solution

  • I believe this is what you are trying to do.

    function cc() {
      return prompt("Choose Character");
    }
    
    function cs() {
      //This will only run the code once, if you wish to have a loop use setInterval()
      setTimeout(function(){      
        var chars = cc(); 
    
        switch (chars) {
          case "spy":
          selectedspy()
          break;
    
          case "bulovian soldier":
          selectedbulovian()
          break;
    
          case "stonian soldier":
          selectedstonian()
          break;
    
          default:
          cs()
      }
    
      }, 3000);
    }