CodeHS JavaScript 计时器 - 倒计时

CodeHS JavaScript Timer- Countdown

我在 CodeHS 上工作,需要为我正在制作的游戏 Breakout 中的道具制作一个倒数计时器。我需要计时器可以重复使用,所以没有 for 循环,它需要在 seconds/milliseconds 内下降(哪个无关紧要)并且最好持续 30 秒或 30,000 毫秒。请记住,这是我正在研究的 CodeHS。

如果我错了请告诉我,因为我不知道 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);}

如果您希望在启动计时器后 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 不想要硬编码数字(我想他们称它们为 "magic numbers"),请将 30s 替换为设置为 30 的常量。

如果您需要更好的解释,请告诉我。