我有一个javascript代码,可以在页面启动时加载提示:“你相信......” 得到答案。返回“我看到”警报,无论用户输入什么,等待10,000毫秒然后进入第二个提示。不知道我做错了什么。当我删除超时功能及其下面的所有内容时,提示工作正常,但不确定如何使其余工作。
<!DOCTYPE html>
<html>
<head>
<title>T-Master, what drink would you like?</title>
</head>
<body>
<script>
window.onload=first();
function first(){
var answer = prompt("Do you believe you have the power to change the world?");
switch(answer){
default:
alert("...I see");
setTimeout(function(){
//do what you need here
},
10000);
}
var answer2 = prompt("Master, your drink?");
var text;
switch(answer2){
case "Gatorade":
text = "THat's what I thought sire";
break;
case "Orange Juice":
text = "That's a good choice sir";
break;
case "Bliss"
text = "Hmm, a finer choice than what I expected";
break;
case "nothing";
text = "Very well sir";
break;
default:
text = "I'll get on it";
break;
}
alert(text);
}
</script>
</body>
</html>
答案 0 :(得分:-3)
你可以混合使用异步和同步编程。您的prompt
呼叫是同步的,但setTimeout
是异步的,并且会在之后的代码之后执行。
window.onload=first();
function first() {
var answer = prompt("Do you believe you have the power to change the world?");
switch(answer) {
default :
alert("...I see");
setTimeout(function() {
//do what you need here
var answer2 = prompt("Master, your drink?"),
text;
switch(answer2) {
case "Gatorade" :
text = "That's what I thought sire";
break;
case "Orange Juice" :
text = "That's a good choice sir";
break;
case "Bliss" :
text = "Hmm, a finer choice than what I expected";
break;
case "nothing" :
text = "Very well sir";
break;
default :
text = "I'll get on it";
break;
}
alert(text);
}, 10000);
}
}