2014-11-20 76 views
0
<div id="counter">1:00</div> 
function countdown() { 
var secs = 60; 
function tick() { 
    var counter = document.getElementById("counter"); 
    secs--; 
    counter.innerHTML = "0:" + (secs < 10 ? "0" : "") + String(secs); 
    if(secs > 0) { 
     setTimeout(tick, 1000); 
    } else { 
     alert("Game Over"); 
    } 
} 
tick(); 
} 

countdown(60); 

我遇到了這部分遊戲的問題。我試圖設置一個60秒計時器,該計時器的開始時間是60分鐘,結束時間是0分鐘,當分數達到0時,遊戲停止,警報顯示遊戲結束。在JavaScript記憶輔助遊戲中設置一分鐘計時器

我對編程非常陌生,所以請給我儘可能多的反饋。我在互聯網上發現了這個代碼,我想到了它的大部分內容,你能不能告訴我tick()函數在這裏做了什麼?蜱的

+0

「tick()函數做了什麼?」考慮到代碼只不過是'tick',那麼你是什麼意思?「我弄清楚了大部分內容」。你需要什麼特別的幫助? – 2014-11-20 19:50:54

回答

0

這裏有一種方法可以做到這一點:

首先聲明將用於間隔的變量(應該是「全球性」,附加於窗):

var countDownInterval = null; 

然後,一個觸發滴答間隔的函數,每當遊戲準備開始時您應該調用它:

function startCountDown() 
{ 
    countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms 
} 

wh ICH將調用蜱功能每秒:

function tick() 
{ 
    // Check to see if the counter has been initialized 
    if (typeof countDownInterval.counter == 'undefined') 
    { 
     // It has not... perform the initialization 
     countDownInterval.counter = 0; //or 60 and countdown to 0 
    } 
    else 
    { 
     countDownInterval.counter++; //or -- 
    } 


    console.log(countDownInterval.counter); //You can always check out your count @ the log console. 

    //Update your html/css/images/anything you need to do, e.g. show the count. 

    if(60<= countDownInterval.counter) //if limit has been reached 
    { 
     stopGame(); //function which will clear the interval and do whatever else you need to do. 
    } 

} 

,然後功能,你可以做你需要做的比賽結束後一切:

function stopGame() 
{ 
    clearInterval(countDownInterval);//Stops the interval 
    //Then do anything else you want to do, call game over functions, etc. 
} 

您可以在任何時候火起來的反通過調用startCountDown();

0

僞代碼:

function tick() { 
    reduce counter variable; 
    if counter > 0 
     wait for 1 second; (This is what setTimeout(tick, 1000) means) 
     call tick() again (recursively) 
    } 
    else { 
    game over 
    } 
} 
0

像這樣的事情?

var countdown = function(sec, tick, done) { 
    var interval = setInterval(function(){ 
     if(sec <= 0) { 
      clearInterval(interval); 
      done(); 
     } else { 
      tick(sec) 
      sec--; 
     } 
    }, 1000) 
} 

countdown(10, console.log, function(){console.log('done')})