CodeHS JavaScript Timer-倒计时

问题描述 投票:0回答:3

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

javascript countdowntimer
3个回答
0
投票

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

0
投票

如果您想在启动计时器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")
    }
}

添加你的功能或任何你想要发生的时间到达whereprintln("Done")

因为timeRemaining在结尾处被设置为30,所以您可以通过再次调用setTimer(countdown, 1000)来重用计时器。

你可以删除println的声明,它们只是为了看看发生了什么。

如果CodeHS不想要硬编码的数字(我认为他们称之为“幻数”),请将30s替换为常数设置为30。

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


-1
投票
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);}
© www.soinside.com 2019 - 2024. All rights reserved.