我在修改Javascript遊戲,並需要在遊戲板頂部添加倒數計時器(從3:00分鐘到0秒)。我將遊戲和計時器都寫入了,當用戶點擊遊戲的「開始」按鈕時,計時器就會啓動。 (即遊戲時間到3分鐘後結束)Javascript game with timer
我的問題是,由於JavaScript不是多線程的,我的遊戲倒數計時器將不允許在用戶同時玩我的遊戲時運行(打勾) 。那是對的嗎?
在我看來,除了使用新的多線程JavaScript庫之外,還有一些方法可以使其發揮作用。
這裏是我的計時器:
<script type="text/javascript">
// set minutes
var mins = 3;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs/60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
<script>
countdown();
</script>
<div id="timer">
<input id="minutes" value="3" type="text" style="width: 14px; border: none; background-color:none; font-size: 16px; font-weight: bold;">:<input id="seconds" value="00" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;"> remaining
</div>
下面是踢一切都關掉我的遊戲的一部分:
<script>
$(function(){
$("#button-start").click(game.start);
});
</script>
我怎麼有game.start
方法運行以及從countdown()
方法我的計時器?每次我嘗試在單擊「開始」時運行這兩種方法時,JavaScript都根本不運行。沒有任何工作,它凍結了,我假設從兩個方法試圖立即運行?
不,這是不正確的。定時器仍然運行。 – 2013-02-28 21:16:59
我們如何在沒有您的代碼的情況下提供幫助?你是否使用for循環代替setTimeout進行倒計時? – 2013-02-28 21:17:02
「玩遊戲」不是一個同步的,瀏覽器凍結的3分鐘持續腳本執行,是嗎?計時器將有機會在事件循環期間觸發。 – Bergi 2013-02-28 21:26:28