這裏有一種方法可以做到這一點:
首先聲明將用於間隔的變量(應該是「全球性」,附加於窗):
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();
「tick()函數做了什麼?」考慮到代碼只不過是'tick',那麼你是什麼意思?「我弄清楚了大部分內容」。你需要什麼特別的幫助? – 2014-11-20 19:50:54