Date.now()
Date.now()
静态方法返回自 epoch 以来经过的毫秒数,epoch 定义为 UTC 1970 年 1 月 1 日开始的午夜。
¥The Date.now()
static method returns the number of milliseconds elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.
Try it
语法
参数
返回值
描述
时间精度降低
¥Reduced time precision
为了提供针对定时攻击和 fingerprinting 的保护,Date.now()
的精度可能会根据浏览器设置进行舍入。在 Firefox 中,privacy.reduceTimerPrecision
首选项默认启用,默认值为 2 毫秒。你还可以启用 privacy.resistFingerprinting
,此时精度将为 100ms 或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds
的值,以较大者为准。
¥To offer protection against timing attacks and fingerprinting, the precision of Date.now()
might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision
preference is enabled by default and defaults to 2ms. You can also enable privacy.resistFingerprinting
, in which case the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds
, whichever is larger.
例如,在降低时间精度的情况下,Date.now()
的结果将始终是 2 的倍数,或者在启用 privacy.resistFingerprinting
的情况下是 100 的倍数(或 privacy.resistFingerprinting.reduceTimerPrecision.microseconds
)。
¥For example, with reduced time precision, the result of Date.now()
will always be a multiple of 2, or a multiple of 100 (or privacy.resistFingerprinting.reduceTimerPrecision.microseconds
) with privacy.resistFingerprinting
enabled.
// reduced time precision (2ms) in Firefox 60
Date.now();
// Might be:
// 1519211809934
// 1519211810362
// 1519211811670
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
Date.now();
// Might be:
// 1519129853500
// 1519129858900
// 1519129864400
// …
示例
测量经过的时间
¥Measuring time elapsed
你可以使用 Date.now()
获取当前时间(以毫秒为单位),然后减去之前的时间来找出两次调用之间经过了多少时间。
¥You can use Date.now()
to get the current time in milliseconds, then subtract a previous time to find out how much time elapsed between the two calls.
const start = Date.now();
doSomeLongRunningProcess();
console.log(`Time elapsed: ${Date.now() - start} ms`);
对于更复杂的场景,你可能需要使用 性能 API。
¥For more complex scenarios, you may want to use the performance API instead.
规范
Specification |
---|
ECMAScript Language Specification # sec-date.now |
浏览器兼容性
BCD tables only load in the browser