gpt4 book ai didi

javascript - 如何实时显示 Javascript 输出?

转载 作者:行者123 更新时间:2023-11-29 20:43:35 25 4
gpt4 key购买 nike

如果这是一个简单的问题,我们深表歉意,但是有没有一种方法可以将 Javascript 实时输出到控制台,同时在每次用户交互时暂停。换句话说,如果我做一些像...这样简单的事情

console.log("What's your name: ");
let userName = prompt("What is your name?");
console.log(userName);

console.log("\n");

console.log("Nice to meet you " + userName + "! What is your age?");
let userAge = prompt("What is your age?");
console.log(userAge);

...我可以在年龄提示出现之前将名字输出到屏幕吗?这在其他教学环境(MS Basic 和命令提示符)中是可行的,但要么在 Javascript 中不存在,要么我遗漏了一些东西。

感谢您帮助新人!

最佳答案

你可以使用 setTimeout,像这样:

console.log("What's your name: ");
let userName = prompt("What is your name?");
console.log(userName);

console.log("\n");
setTimeout(function(){
console.log("Nice to meet you " + userName + "! What is your age?");
let userAge = prompt("What is your age?");
console.log(userAge);
},1000)

注意:这是一种方法,还有很多其他方法可以做到。

如果你想使用 promises:

let userName,userAge, userSport;
function basic(){
console.log("What's your name: ");
var promise1 = new Promise(function(resolve, reject){
userName = prompt("What is your name?");
resolve(userName)
})
promise1.then(function(value){
console.log(value);
console.log("\n");
console.log("Nice to meet you " + value + "! What is your age?");
var promise2 = new Promise(function(resolve, reject){
userAge = prompt("What is your age?");
resolve(userAge)
})
promise2.then(function(value){
console.log(value)
console.log("Nice to meet you " + userName + " aged: " +userAge + ". Let us know your favorite sports")

var promise3 = new Promise(function(resolve, reject){
userSport = prompt("What is your favorite sports?");
resolve(userSport)
})
promise3.then(function(value){
console.log(value)
console.log("Nice to meet you " + userName + " aged: " +userAge + " and your favorite sports is " +value)
console.log("\n");
console.log("Thanks");
})
})
})

}
basic()

关于javascript - 如何实时显示 Javascript 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com