我有一个javascript代码,它在页面启动时加载一个提示:“您相信.”得到答案。返回“我看到”警报,不管用户输入什么,等待10,000毫秒,然后输入第二个提示符。不知道我做错了什么。当我删除超时函数及其下面的所有内容时,提示工作正常,但不确定如何使rest工作。
<!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>发布于 2015-08-13 15:23:15
这里有异步和同步编程的混合体。您的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);
}
}https://stackoverflow.com/questions/31992246
复制相似问题