I’m trying to make a game using a website called CodeHS, and it needs a time limit. I’m trying to achieve this through graphic text on a canvas that counts down from 2 minutes, but it isn’t working. I’m a new coder, just started in August, so my coding is likely not the most efficient, but my knowledge of JavaScript is limited. Can someone help?
This is what my code looks like:
const CENTER_X = getWidth() / 2;
const TIMER_MINUTES = 2;
const TIMER_SECONDS = 0;
function timer(){
var timerMinutes = TIMER_MINUTES;
var timerSeconds = TIMER_SECONDS;
var timer = new Text(timerMinutes + ":0" + timerSeconds, "17pt Arial");
timer.setPosition(CENTER_X - 21, 18);
timer.setColor(Color.white);
add(timer);
while(true){
if(timerSeconds == 0){
if(timerMinutes == 0){
setTimeout(function() { timer.setText("0:00") }, 1000);
// gameOver();
break;
}
timerMinutes -= 1;
timerSeconds += 59;
}else{
timerSeconds -= 1;
}
if(timerSeconds < 10){
setTimeout(function() { timer.setText(timerMinutes + ":0" + timerSeconds) }, 1000);
}else{
setTimeout(function() { timer.setText(timerMinutes + ":" + timerSeconds) }, 1000);
}
}
}
When I run the code, the text "2:00" successfully pops up, but then a second later it changes to "0:00" without counting down. For clarification, I’ve turned gameOver(); into a comment because the function in my code is not relevant to how the timer’s code should run.
2
Answers
Your problem is that the statements in the while() loop do not wait for any of the timeouts, they just decrement the minutes and seconds as fast as they can.
So remove the while() and break statements. Move the variables outside the function so they keep their values between function calls.
Change the name of your string variable so that is not the same as the function name.
I ran this successfully on the codehs website.
You can use countdown.js JavaScript file. I implemented this library to create countdown timer so easy and fast. You can get it from this link on my github.