多个提示之间的Javascript-Console.log [英] Javascript- Console.log between multiple prompts

查看:60
本文介绍了多个提示之间的Javascript-Console.log的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很确定很多人都遇到过这种情况。例如:您有一个简单的JS选择您自己的冒险游戏。

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

发生的情况是显示第一个提示,然后紧接着显示第二个提示(年龄)。另外,在您回答两个提示后,控制台甚至不会打印出 Hello +(名称)。无论如何,您是否可以在两个提示之间强制打印 console.log?

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?

推荐答案

问题是用户界面的更新速度快于JavaScript的执行速度,这导致与 console.log 语句同步时出现问题。

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.

发生这种情况是因为JavaScript运行时不负责更新UI,这是浏览器的工作,因此一旦JavaScript要求浏览器更新UI(显示提示) ,它会非常快速地执行此操作,并且由于 propmt 是一个阻止对话框,因此所有其他代码都将被暂停。

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

这篇关于多个提示之间的Javascript-Console.log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆