<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结束,当游戏停止并且警报显示游戏结束时。
我对编程很陌生,所以请尽可能多地给我反馈。我在互联网上找到了这个代码,我想出了大部分代码,你能告诉我tick()函数在这里做了什么吗?
答案 0 :(得分:0)
tick的伪代码:
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
}
}
答案 1 :(得分: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')})
答案 2 :(得分:0)
以下是一种方法:
首先声明一个用于间隔的变量(应该是'global',附加到窗口):
var countDownInterval = null;
然后,一个触发滴答间隔的功能,你应该在游戏准备开始时调用它:
function startCountDown()
{
countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms
}
将每秒调用tick函数:
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();