Ivo
Ivo

Reputation: 2636

time in countdown to minutes and seconds

I'm Having a little script to countdown

http://jsfiddle.net/yv4H4/

one of the problems is going from seconds to a better readable 0:00

the other problem is the time it takes for the countdown to start

edit: I think I mixed up with a little php

window.onload = function() {
    canvas  = document.getElementById('timer'),
    seconds = document.getElementById('counter'),
    ctx     = canvas.getContext('2d'), 
    sec     = seconds.innerHTML | 0,
    countdown = sec;

ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";

var 
startAngle = 0, 
time       = 0,
mins       = 0,
secs       = 0,
intv       = setInterval(function(){

    // Making 180 look like 3:00 is not working 
    if(sec > 59)
{
    mins = Math.floor(sec/60);
    secs = Math.floor(sec - mins*60);


    if(mins < 10) mins = "0" + mins;
    if(secs < 10) secs = "0" + secs;
}

    var endAngle = (Math.PI * time * 2 / sec);
    ctx.arc(50, 50, 35, startAngle , endAngle, false);   
    startAngle = endAngle;
    ctx.stroke();

    seconds.innerHTML = countdown--;

    if (++time > sec) { clearInterval(intv); }

}, 1000);

Upvotes: 2

Views: 384

Answers (1)

JCOC611
JCOC611

Reputation: 19709

The delay in the countdown is caused by it being linked to the window.onload event, which only fires when all the content of the page has been loaded (hence the time it takes for it to start). If you would like for it to fire faster, I recommend you look into the DOM ready event. (Like this for example).

As for the "better readable 0:00", I've made a jsFiddle with a simple solution:

countdown--;
seconds.innerHTML = Math.floor(countdown/60);
seconds.innerHTML += ":" + countdown%60;

Which takes the division of the current time by 60 (and rounded down to the nearest integer) as the minutes, and the reciprocal of such division as the seconds.

Upvotes: 2

Related Questions