单调增加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()
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.
推荐答案
您可以使用窗口.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屋!