Date.now() 在浏览器中的准确性

Accuracy of Date.now() in browsers

我看到很多关于如何在 JavaScript 中获得 date/time 的问题,答案总是类似于

Date.now() returns the UTC timestamp in milliseconds

但是这个值到底有多可靠?它是否仅基于 运行 浏览器所在计算机的系统时钟?如果是这样,它似乎可能与真正的 UTC 时间相差很远,但应该预期有多少变化?我知道关心精确的毫秒是一个失败的原因,但是秒或分钟的数量级呢?

Is it just based on the system clock of whatever computer is running the browser?

没错。它很可能是完全不准确的。例如,在我的计算机上,它的时钟不准确,此时,Date.now() returns 1563724931361,当传入 new Date 时,给出:

Sun Jul 21 2019 11:02:11 GMT-0500 (Central Daylight Time)

这是完全错误的。

如果客户希望提供不准确的 Date.now(),他们这样做是微不足道的,尽管 通常 ,对于大多数普通用户来说,这将是准确,因为 大多数 人的时钟准确。

有多准确?这取决于硬件,取决于他们的计算机上次从时间服务器请求时间以来的时间,以及计算机打开后的时间(关闭电源或 standby/hibernate),但大多数时候,不会超过一分钟。

总有ECMA-262:

20.3.3.1 Date.now ( )

The now function returns a Number value that is the time value designating the UTC date and time of the occurrence of the call to now.

就是这样,对值的来源或其准确性没有要求,因此它取决于实现。在实践中,似乎大多数实现都使用来自主机系统的值,因此可靠性并不比系统时钟和用户提供的设置(如日历、时区、夏令时、当前时间等)的预期更好

鉴于side-channel memory attacks the accuracy of the timing sources in a browser were limited. According to current information, from W3C High Resolution Time issue tracker,不同浏览器的限制略有不同:

  • 移动Chrome + 边缘:100us + 100us 抖动
  • 桌面Chrome:5us
  • Safari + Firefox:1 毫秒