毫秒倒计时/计时器似乎停在零

millisecond countdown/timer seems to pause on zero

本文关键字:计时器 倒计时      更新时间:2023-09-26

创建一个简单的毫秒倒计时/定时器,下面是一个使用jsFiddle的实例

我的问题是数字0比其他数字显示的时间更长。

我想要一个流畅的倒计时,有什么建议吗?

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);
如果需要

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;
}

看起来,如果你把字符串转换,暂停消失:

var milliseconds = distance % (_second / 100);

代替

var millisecond = getDigit(1, milliseconds);
http://jsfiddle.net/c3ncA/3/