简体   繁体   中英

Javascript/JQuery wait for user input

I'm working on a text-based browser game made using Javascript and JQuery. I've run into a problem with user input. What I used to do was just use a prompt() because it was easy to use, allowed me to save the input to a variable and made the code wait for input.

Now I want it to look better, so I've made my own input field with a nice chatbox above it. What I wanted to know was how to stop the code from executing untill the user has pressed enter (I already detect the enter press and the text is being appended to the dialog box, I just need the code to wait for that to happen before it continues).

Here's some of my code:

Function for input

function input_field() {
    var inputField = $('#dialog-input');
    var messageField = $('#dialog-text');

    inputField.keyup(function (e) {
        if (e.keyCode == 13) {
            window.userInput = inputField.val();
            if(userInput != '') {
                messageField.append('You: ' + window.userInput + '<br>');
                inputField.val('');
                messageField.scrollTop(999999999);
            }
        }
    });
}

What I'd like to do is just save the data to a variable and then check it with a switch-case just like with prompt() , but as it stands now it just gives me an error because it tries to execute all the code instead of wait untill the user has given input.

It is possible with asynch+await.

Please note, that it is currently not fully supported by all browsers ( http://caniuse.com/#search=await ) and that there are probably better solutions to this kind of problems.

Using await myAsyncFunction() makes the browser treat the function like it is synchrounous, therefore it stops further execution of this function until a result is returned by the awaited function. It does not block other code on the website from running.

await may only be used inside a async function , otherwise the browser will throw an error.

Here is an example showing how you could wait for user input with await+async:

 async function handleForm() { let userInput = ''; console.log('Before getting the user input: ', userInput); userInput = await getUserInput(); console.log('After getting user input: ', userInput); }; function getUserInput() { return new Promise((resolve, reject) => { $('#myInput').keydown(function(e) { if (e.keyCode == 13) { const inputVal = $(this).val(); resolve(inputVal); } }); }); }; handleForm();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="myInput">

You have to thing differently, while javascript stop and wait for a returned value when using prompt(), you can't directly achieve that with a custom prompt.

var result = [];
for(var i = 0; i > 5; i--){
    result.push( prompt('tip something') ); // Ok
};

javascript will break until prompt return something

but you can't tell your code to stop, like the browser does when promprting. You'll have to execute a code when closing the modal (on button click or keypress enter) that open/update the next modal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM