Skip to content Skip to sidebar Skip to footer

Javascript- Console.log Between Multiple Prompts

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. what happens is the first prompt is shown

Solution 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);

Solution 2:

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.


Post a Comment for "Javascript- Console.log Between Multiple Prompts"