Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Date.now() in one object declaration

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

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

like image 493
Randomblue Avatar asked Sep 08 '15 14:09

Randomblue


People also ask

What does new Date () return?

"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.

What is new Date () in JavaScript?

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.


1 Answers

No.

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.

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

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

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.

like image 56
ssube Avatar answered Oct 06 '22 00:10

ssube