`setTimeout`设置为1,为什么我的时钟跳过秒?

时间:2015-01-11 16:12:24

标签: javascript animation

我正在使用十进制时钟(100min 10 / hr& 100s 10 / min 10)。 The code正在跳过十进制秒数(在Ubuntu 14和Android中的Firefox和Chrome中)。 setTimeout的延迟为1。

function updateTime() {
    var now = new Date()
    var h = now.getHours();
    var m = now.getMinutes();
    var s = now.getSeconds();
    document.getElementById('babylonian').innerHTML = h+":"+padDigit(m)+":"+padDigit(s)
    document.getElementById('decimal').innerHTML = h + "h" + padDigit( Math.round( ( 100 * m ) / 60) ) + "." + padDigit( Math.round( ( 100 * s ) / 60 ) )

    setTimeout(updateTime, 1);
}

function padDigit(i) {
    return i<10 ? '0' + i : i
}

updateTime()

时钟似乎在同步。我不明白为什么。

1 个答案:

答案 0 :(得分:4)

这是因为有100&#34;十进制秒&#34;每分钟,但只有60秒。因此,对于每一秒,都有100/60&#34;十进制秒&#34;。

当您在now.getSeconds()上进行计算时,您将在&#34;十进制秒数&#34;中获得跳跃。

使用更细粒度的内容,例如now.getMilliseconds()

var s = now.getSeconds() + now.getMilliseconds()/1000;
...
...  ...  ... Math.floor(  s * 100  / 60 )  ...

(并且在分钟内做同样的事情以避免跳过小数分钟。)