2017-04-06 49 views
1

製作一個小遊戲,玩家必須猜測存儲的是什麼顏色。 預期的最終結果是,當玩家正確猜測消息顯示並且背景顏色改變時。然而,我的背景顏色只有在你關閉對話框後纔會改變。背景顏色變化的意外延遲

這裏是代碼。有問題的部分是在最後

<!DOCTYPE HTML> 
<html> 
<body onload="do_game()"> 

<script> 
var colors = ["blue","red","yellow","green","brown", 
      "magenta","purple","aqua","coral", 
      "violet","pink","grey","cyan","black","white"]; 
var target; 
var guess_count = 0; 
var guess_input; 
var game_end; false; 

function do_game(){ //Start of function do_game // 
     colors.sort(); 
     target = Math.floor(Math.random() * colors.length); 
     alert(colors[target]); 

     do { 
     guess_input = prompt(
     "I am thinking of one of these colors \n\n" + 
     colors +"\n\nWhat color am I thinking of?") 

     guess_count ++; 

     } 
     while (check_guess()); 
     } //end of function do_game // 

function check_guess(){ //start of function check_guess// 
     var color_guess = colors.indexOf(guess_input); 
     if (color_guess < 0) 
      alert("I don't recognise that color!\n\n" 
       + "Please try again"); 
     else if (color_guess < target) 
      alert("Sorry your guess is not correct!\n\n" 
       + "Hint: Your guess is aphebetically lower\n\n" 
       + "Please try again!"); 
     else if (color_guess > target) 
      alert("Sorry your guess is not correct!\n\n" 
       + "Hint: Your guess is aphebetically higher\n\n" 
       + "Please try again!"); 
     else { 
      document.body.style.background = colors[target]; 
      alert("Congratulations!\n\n" + "You guessed " + colors[target] 
       + "\n\nThis is correct!\n\n" 
       + "It took you " + guess_count + " guesses"); 
      return false; 
     } 
      return true; 
     } 
</script> 
</body> 
</html> 
+0

您正在使用一個警告框,它將停止執行Javascript,直到它被回覆。您應該使用通知'div'(或類似的東西)與用戶溝通。 – Sablefoste

回答

0

問題是,alertboxes停止JavaScript的流程,直到他們被迴應。你可以解決這個問題通過設置警告框前一毫秒的延遲被調用時,通過使用setTimeout功能:

else { 
    document.body.style.background = colors[target]; 
    setTimeout(makeTimeoutFunc(), 1); // 1 millsecond 
    return false; 
} 

...

function makeTimeoutFunc() { 
    return function() { 
     alert("Congratulations!\n\n" + "You guessed " + colors[target] + "\n\nThis is correct!\n\n" + "It took you " + guess_count + " guesses"); 
    } 
} 

我創建了一個展示的jsfiddle這here

希望這會有所幫助! :)

+0

太棒了!學到新東西,解決了我的問題。乾杯夥計:) – ConorHalpin