【发布时间】:2017-02-13 23:47:08
【问题描述】:
我在 CodeHS 工作,需要在我正在制作的游戏 Breakout 中为我的通电做一个倒计时。我需要计时器是可重复使用的,所以没有 for 循环,它需要在几秒/毫秒内下降(不管哪个),最好持续 30 秒或 30,000 毫秒。请记住,这是我正在开发的 CodeHS。
【问题讨论】:
-
请展示你做了什么(你的代码)。
我在 CodeHS 工作,需要在我正在制作的游戏 Breakout 中为我的通电做一个倒计时。我需要计时器是可重复使用的,所以没有 for 循环,它需要在几秒/毫秒内下降(不管哪个),最好持续 30 秒或 30,000 毫秒。请记住,这是我正在开发的 CodeHS。
【问题讨论】:
如果您希望在启动计时器 30 秒后发生某些事情,您可以执行以下操作:
//set the time remaining to 30 outside of a function so it is global
var timeRemaining = 30;
function start(){
//set the timer to run the function countdown once every second(1000 milliseconds)
setTimer(countdown, 1000)
}
function countdown(){
/*every time it is called this function subtracts one from the time if it is
more than 30, when it reaches 0 stops the timer and resets the time*/
if(timeRemaining<=0){
stopTimer(countdown);
timeRemaining = 30;
println("Done");
//30 seconds has passed, do what you need here(call your function)
}else{
timeRemaining--;
println(timeRemaining+" seconds left")
}
}
在println("Done")所在的时间结束后添加您的函数或任何您想发生的事情。
因为timeRemaining最后被设置回30,你可以通过再次调用setTimer(countdown, 1000)来重用定时器。
您可以删除println 状态,它们只是为了看看发生了什么。
如果 CodeHS 不想要硬编码数字(我认为他们称它们为“幻数”),请将 30 替换为设置为 30 的常量。
如果您需要更好的解释,请告诉我。
【讨论】:
如果我错了,请告诉我,因为我不知道 CodeHS 是什么,但我很确定这可以通过一个简单的 setInterval 函数来实现。
整秒:
var timer=30;
setInterval(function(){
timer-=1;
document.getElementById(timerId). innerHTML=timer;//shows the remaining time
}, 1000);//subtracts 1 second from timer each second
相差十分之一秒
var timer=30.0;
setInterval(function(){
timer-=0.1;
document.getElementById(timerId). innerHTML=timer;//shows the remaining time
}, 1000);//subtracts a tenth second from timer every 0.1 seconds
【讨论】:
var timeLeft = 60;
var txt = new Text(" ","30pt Arial");
function start(){txt.setPosition(200,200); txt.setColor(Color.black); add(txt); setTimer(countdown,1000);}
function countdown(){drawTimer(); timeLeft--;}
function drawTimer(){txt.setText(timeLeft);}
【讨论】: