制作一个简单的毫秒倒计时/计时器,这里是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;
}
答案 0 :(得分:1)
看起来如果你取出字符串转换,暂停就会消失:
var milliseconds = distance % (_second / 100);
而不是
var millisecond = getDigit(1, milliseconds);