Kristian
Kristian

Reputation: 89

How to change the countdown timer into minutes : seconds?

I am designing the game like that, but the countdown timer is still in seconds. So I want to change it into minutes : seconds. How can I change it into minutes : seconds? Please give me an explanation.

//thanks to GameAlchemist
function createCountDown(timeRemaining) {
    var startTime = Date.now();
    return function() {
    return timeRemaining - ( Date.now() - startTime );
    }
}
var currentCountDown = createCountDown(30000);
// Draw everything
var render = function () {
var countDownValue = currentCountDown();
returnKillsNeeded(stageNum);
    ctx.drawImage(startGameImg, 0,0);
    ctx.font = "24px Helvetica";
    ctx.textAlign = 'center'
    ctx.textBaseline = "top";
    ctx.fillStyle="#FF0000";
    ctx.fillText("press Enter to play", 250, 450);
    ctx.fill();
    if(gameStart){
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
ctx.fillStyle="#522900";
ctx.fillRect(0,480,500,120);
ctx.drawImage(scoreImg, 22,522);
ctx.drawImage(livesImg, 360,522);
ctx.drawImage(progressImg, 200,492);
createProgressBar();
createProgressPercent();
ctx.fillText("progress", 170,492);
setEnemyHealthText();
drawPlayer();
if(countDownValue <=0){
    countDownValue = 0;
}else{
    ctx.fillText(countDownValue, 200,190);
}

Upvotes: 1

Views: 275

Answers (3)

trincot
trincot

Reputation: 350137

Replace:

ctx.fillText(countDownValue, 200,190);

By:

// Convert miliseconds to seconds.
var seconds = Math.floor(countDownValue/1000);
// A minute is 60 seconds. See how many times 60 fits in the number of seconds:
var minutes = Math.floor(seconds / 60);
// Calculate how many seconds are left when removing those minutes:
seconds -= minutes * 60;
// Format the seconds to always have 2 digits
seconds = seconds.toFixed(2);
// Output the result:
ctx.fillText(minutes + ':' + seconds, 200, 190);

Some comments:

If using a plug-in is OK for you, then don't reinvent the wheel. For instance: jQuery Countdown.

The code you provided has unbalanced braces. That should of course be fixed before your code can run.

Upvotes: 0

pr0gramista
pr0gramista

Reputation: 9008

1 minute is 60 seconds, right?

Divide countDownValue by 60 to get minutes and round it downwards fe. using Math.floor() to make it clean. Modulo countDownValue by 60 to get seconds.

var minutes = Math.floor(countDownValue/60);
var seconds = countDownValue%60;

Then to print time like MM:SS

if(seconds > 9)
    ctx.fillText(minutes + ":" + seconds, 200,190);
else
    ctx.fillText(minutes + ":0" + seconds, 200,190);

This if statement is to always print time as 7:06, not 7:6

Upvotes: 1

c0l3
c0l3

Reputation: 823

convert you millis into minutes and seconds

if(countDownValue <=0){
    countDownValue = 0;
}else{
    ctx.fillText(
       (countDownValue/1000/60) << 0 + 
       ':' + 
       (countDownValue/1000) % 60, 200, 190
    );
}

Upvotes: 0

Related Questions