2015-10-15 81 views
3

我正在製作Nest的Smoke and Carbon Monoxide Alarm Nest Protect的模擬器。但是當我按下按鈕(點擊)內環不會按照它應該變成藍色。它說話,就像我使用ResponsiveVoice一樣,但它不會亮起來!這是我的(未完成的)代碼。Javascript img change聲明過早過早

<script src="http://code.responsivevoice.org/responsivevoice.js"></script>  
<script> 
function delay(millis) { 
    var date = new Date(); 
    var curDate = null; 
    do { curDate = new Date(); } 
    while(curDate-date < millis); 
} 
function press() { 
    document.getElementById("unit").src = "assets/img/blue.jpg"; 
    delay(500); 
    responsiveVoice.speak("Ready. In the Living Room. Press to test."); 
    delay(500); 
    document.getElementById("unit").src = "assets/img/idle.jpg"; 


} 
</script> 
+1

因爲JavaScript運行在單個線程上,並且如果JavaScript執行停留在while循環中,您應該真的考慮使用'setTimeout'來代替硬延遲,頁面將凍結。 – yvesmancera

回答

7

你可以試試這個:

function delay(millis, action) { 
    setTimeout(action, millis); 
} 

function press() { 
    document.getElementById("unit").src = "assets/img/blue.jpg"; 
    delay(500, 
     function() { 
      responsiveVoice.speak("Ready. In the Living Room. Press to test."); 
     } 
    ); 
    delay(1000, 
     function() { 
      document.getElementById("unit").src = "assets/img/idle.jpg"; 
     } 
    ); 
} 

這是更好,因爲大多數瀏覽器都使用一個單獨的線程JavaScript的當前的功能將會使頁面響應在等待使用的setTimeout或setInterval的。這使您可以異步執行其他任務。

+0

它的工作!不得不改變它5秒,但它的工作!非常感謝! – ry00000

+0

沒問題!樂於幫助! – AtheistP3ace

+0

@Gargano嘿,如果你覺得這個答案解決了你的問題,並幫助將介意接受它作爲答案?試圖獲得特權的代表點!謝謝! – AtheistP3ace