2015-08-13 22 views
0

我有一個JavaScript代碼,加載頁面啓動時的提示:「你相信...」 獲取答案。無論用戶輸入什麼,都會返回「我看到」警報,等待10,000毫秒,然後輸入第二個提示。不知道我做錯了什麼。當我刪除超時功能及其下的所有內容時,提示符工作正常,但不知道如何讓其餘的工作。Javascript:setTimeout和多個提示

<!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

爲什麼你會使用開關,然後不做任何事情,但使用默認值? –

+0

「等待10,000毫秒」 - 不,它不。這不是'setTimeout'的作用。 – Quentin

+0

「,然後輸入第二個提示」 - 顯然,同樣。 – Quentin

回答

-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); 
    } 
} 
+0

上歡呼我,你的onload是錯誤的,這將解僱,而不是在窗口加載... –

+0

剛剛離開什麼OP第一次有。問題不在於這裏,問題是同步vs異步。 –

+0

是的,他也有一些你修正的語法錯誤,你應該加上一個解釋:P –