首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript: setTimeout和多个Prompts

Javascript: setTimeout和多个Prompts
EN

Stack Overflow用户
提问于 2015-08-13 15:15:20
回答 1查看 363关注 0票数 0

我有一个javascript代码,它在页面启动时加载一个提示:“您相信.”得到答案。返回“我看到”警报,不管用户输入什么,等待10,000毫秒,然后输入第二个提示符。不知道我做错了什么。当我删除超时函数及其下面的所有内容时,提示工作正常,但不确定如何使rest工作。

代码语言:javascript
复制
<!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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-13 15:23:15

这里有异步和同步编程的混合体。您的prompt调用是同步的,但是setTimeout是异步的,将在它后面的代码之后执行。

代码语言:javascript
复制
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);
    }
}
票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31992246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档