2

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);
Ivo
  • 2,588
  • 6
  • 25
  • 43

1 Answers1

2

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.

Community
  • 1
  • 1
JCOC611
  • 19,111
  • 14
  • 69
  • 90
  • @IvoJonkers: I'm glad. I've added a link to another answer in stackoverflow that might help you with firing the countdown on *DOM load*. – JCOC611 Oct 29 '12 at 00:32
  • I never used something else than window.onload so once again thank you ! – Ivo Oct 29 '12 at 00:33
  • 1
    @IvoJonkers: In most cases, `window.onload` should work fine, but it's definitely true that the *DOM load* event fires faster. – JCOC611 Oct 29 '12 at 00:35