In javaScript during a while loop how do you make the program stop to get user input?

97 views Asked by At

So this is what i have, very simplified version of my code. So basically the 'userinput' function needs to know whether the user clicked on button 'run' or 'hit':

html code:

<button id="run">Run</button>
<button id="hit">Hit</button>

javascript code:

slaying = true;
while(slaying){
  //gets user input
  userinput();
  // continue with the rest of the while loop until slaying is true
}

How would you write userinput()??

2

There are 2 answers

1
Saumil On

Instead of using a function "userInput()" you can use events and perform the same steps as you would do inside userInput()

You can use the onclick event as,

<button id="run" onclick="run()">Run</button>
<button id="hit" onclick="hit()">Hit</button>

And write the below script for this as,

function run(){
    alert("You pressed Run");
    //Steps to follow when Run is pressed.
}
function hit(){
    alert("You pressed Hit");
    //Steps to follow when Hit is pressed.
}

Here is a JSFiddle

0
Remy Grandin On

You can use

var response = prompt("Question ?", "Default answer");