2017-02-13 126 views
0

我在CodeHS上工作,需要在我制作的游戏中为我的通电制作倒数计时器,Breakout。我需要定时器是可重复使用的,所以不需要for循环,它需要以秒/毫秒为单位下降(哪个并不重要),并且最好持续30秒或30,000毫秒。请记住,这是我正在开发的CodeHS。CodeHS JavaScript定时器 - 倒计时

+0

请说明你做了什么(你的代码)。 –

回答

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

这在我确定的正常情况下会起作用,但是CodeHS并没有定义很多这些命令。CodeHS对于像I这样的初学者来说有点麻烦。 – wyatt7613

-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);} 
0
10分之

go如果你想要的东西给你启动后发生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

让我知道如果你需要一个更好的解释。