0

Im pretty sure that a lot of people have encountered this situation. For Ex: You have a simple Choose Your Own Adventure game from JS.

    var name = prompt("Name?");
    console.log("Hello" + name);
    var age = prompt("Age?");
    console.log(name + " is " + age + " years old");

what happens is the first prompt is shown and then the second prompt (age) is shown immediately afterwards. Also, the console doesn't even print out the "Hello" + (name) until after you answer the two prompts. Is there anyway you can "force-print" the console.log between the two prompts?

3
  • 1
    Just tried this in chrome and its working as expected... Commented Jun 27, 2017 at 21:17
  • In my version of Chrome (59.0.3071.) it doesn't. In fact, this is a well-known issue with browser generated dialogs. Commented Jun 27, 2017 at 21:20
  • If you are working with prompt(), you might as well use alert() for your outputs. Commented Jul 13, 2017 at 4:41

2 Answers 2

1

The issue is that the UI is being updated faster than the JavaScript is executing and this is causing a problem syncing with the console.log statements.

This happens because the JavaScript runtime is not responsible for updating the UI, that's the browsers job and so once the JavaScript asks the browser to update the UI (display the prompt), it does it very quickly and since a propmt is a "blocking" dialog, all other code is suspended.

Adding a short delay solves the problem:

var name = prompt("Name?");
console.log("Hello " + name);

// Force a 10 millisecond delay before running the rest of the code.
setTimeout(function(){
  var age = prompt("Age?");
  console.log(name + " is " + age + " years old");
}, 10);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Generator functions which are part of the ES6

function * quiz() {
  var name = prompt("Name?");
  yield console.log("Hello" + name);
  var age = prompt("Age?");
  yield console.log(name + " is " + age + " years old");
}

var myQuiz = quiz();
myQuiz.next();
myQuiz.next();

Working demo: https://jsfiddle.net/6mzbhLhz/ - see It in console.

1 Comment

This does exactly the same thing as the original code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.