【问题标题】:millisecond countdown/timer seems to pause on zero毫秒倒计时/计时器似乎停在零
【发布时间】:2014-03-24 20:57:46
【问题描述】:

制作一个简单的毫秒倒计时/计时器,这里是live example using jsFiddle

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

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

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

【问题讨论】:

  • timer = setInterval(showRemaining, 100);让它更流畅
  • @dandavis 看起来好一点,如果你回答而不是评论,我想我已经在 +1 之前设置为 100 值

标签: javascript performance counter countdown


【解决方案1】:

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

var milliseconds = distance % (_second / 100);

而不是

var millisecond = getDigit(1, milliseconds);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多