两个Date.now()在一个对象声明中 [英] Two Date.now() in one object declaration

查看:109
本文介绍了两个Date.now()在一个对象声明中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var o = {a:Date.now(),b:Date.now()}

oa === ob always true ? (我主要对Node.JS感兴趣)

Is o.a === o.b always true? (I am mostly interested in Node.JS.)

推荐答案

否。

在我们进一步了解规范可能会说的情况之前,可以在运行时使用用户定义的函数替换 Date.now 。这在Node和浏览器中都有效:

Before we even get into what the spec might say, Date.now can be replaced with a user-defined function at runtime. This works in both Node and browsers:

let oldNow = Date.now;
Date.now = function () {
  let wait = oldNow() + 1000;
  while (oldNow() < wait) {
    // wait one second
  }
  return oldNow();
}

因此,每次调用至少需要一秒钟,所以你的两个电话将不会相等。

With that, every invocation will take at least one second, so your two calls will never equal.

当我们查看 Date.now (15.9.4.4),它只是说它返回

When we look at the spec for Date.now (15.9.4.4), it simply says that it returns


时间值指定UTC的现在日期和发生时间现在

the time value designating the UTC date and time of the occurrence of the call to now

这不提供两个呼叫的保证一直返回相同的价值。从我可以看出,该规范指定 Date 对象将具有毫秒精度(15.9.1.1),但不能保证准确性。

which provides no guarantees to two calls ever returning the same value. From what I can tell, the spec specifies that Date objects will have millisecond precision (15.9.1.1) but makes no guarantees as to accuracy.

同一行中的两个调用可能会返回同一时间,由于底层定时器不精确,两个发生在同一个勾号中,但规范似乎并未指定。

It is likely that two calls in the same line will probably return the same time, by virtue of the underlying timer being imprecise and the two occurring within the same tick, but the spec does not appear to specify that.

这篇关于两个Date.now()在一个对象声明中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆