Javascript- Console.log between multiple prompts

瘦欲@ 提交于 2019-12-25 08:57:52

问题


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?


回答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);



回答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.



来源:https://stackoverflow.com/questions/44790006/javascript-console-log-between-multiple-prompts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!