Question

making a simple millisecond countdown/timer, here is a live example using jsFiddle

my issue is the number zero displays longer then the other numbers.

I would like a fluid countdown, any suggestions?

JS

// how many seconds will be added to the counter countdown
Date.prototype.addSeconds= function(s)
{
    this.setSeconds(this.getSeconds()+s);
    return this;
}

// default to 60 seconds
var end = new Date().addSeconds(60); // change this value to the seconds wanted for the count down
var _second = 1000;
var _minute = _second * 60;
var timer;

function getDigit(position, number) 
{
    numberString = number + "";
    return numberString.substr (position + 1, 1);
}

function showRemaining()
{
    var countdownElement = document.getElementById('timer');

    var now = new Date();
    var distance = end - now;
    var minutes = Math.floor( (distance % _minute * 60) / _minute );
    var seconds = Math.floor( (distance % _minute) / _second );
    var milliseconds = distance % _second;
    var millisecond = getDigit(1, milliseconds);

    if (millisecond <= 0)
    {
        millisecond = 0;
    }

    countdownElement.innerHTML = seconds + 's ' + millisecond + 'ms';
    //countdownElement.innerHTML = seconds + '.' + milliseconds;

    if (milliseconds < 0) 
    {
       countdownElement.innerHTML = 'Finished';
       clearInterval(timer); 
    }
}

timer = setInterval(showRemaining, 10);

if needed

HTML

<div id="timer">a</div>

CSS

#timer 
{
    display:inline-block;
    padding:3px 5px;
    border:1px solid #666;
    font-family:tahoma;
    color:#999;
    font-size:12px;
}
Was it helpful?

Solution

It looks like if you take the string conversion out, the pause disappears:

var milliseconds = distance % (_second / 100);

instead of

var millisecond = getDigit(1, milliseconds);

http://jsfiddle.net/c3ncA/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top