在 JavaScript 中单调增加时间? [英] Monotonically increasing time in JavaScript?
问题描述
在 JavaScript 中获得单调增加时间的最佳方法是什么?我希望有类似 Java 的 System.nanoTime()
.
What’s the best way to get monotonically increasing time in JavaScript? I’m hoping for something like Java’s System.nanoTime()
.
Date()
显然不行,因为它受系统时间变化的影响.
Date()
obviously won’t work, as it’s affected by system time changes.
换句话说,我想要的是一个 <= b,总是:
In other words, what I would like is for a <= b, always:
a = myIncreasingTime.getMilliseconds();
...
// some time later, maybe seconds, maybe days
b = myIncreasingTime.getMilliseconds();
充其量,即使在 Date()
中使用 UTC 函数时,它也会返回它认为是正确的时间,但如果有人将时间设置向后,则下一次调用 Date()可以返回较小的值.System.nanoTime()
不受此限制(至少在系统重新启动之前不会).
At best, even when using the UTC functions in Date()
, it will return what it believes is the correct time, but if someone sets the time backward, the next call to Date() can return a lesser value. System.nanoTime()
does not suffer from this limitation (at least not until the system is rebooted).
修改: [2012-02-26:无意影响原始问题,有赏金]
Modification: [2012-02-26: not intended to affect the original question, which has a bounty]
我对知道墙上时间"不感兴趣,我有兴趣知道过去时间的准确性,这是 Date()
不可能提供的.>
I am not interested knowing the "wall time", I’m interested in knowing elapsed time with some accuracy, which Date()
cannot possibly provide.
推荐答案
您可以使用 window.performance.now() - 自 Firefox 15 和 window.performance.webkitNow() - Chrome 20]
You could use window.performance.now() - since Firefox 15, and window.performance.webkitNow() - Chrome 20]
var a = window.performance.now();
//...
var delay = window.performance.now() - a;
这篇关于在 JavaScript 中单调增加时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!