Reputation: 12400
Here is a code snippet i've come across for creating uniqueIDs in a script.
var now = (new Date()).valueOf();
var future = (new Date()).valueOf();
while(future == now){
future = (new Date()).valueOf();
}
return future;
My question is, why use .valueOf()
instead of .getTime()
and is the purpose of two date objects and a while loop to avoid the change of returning the same values if called multiple times. Surely the chances of returning the same millisecond representation of the date are slim to none? Any thoughts?
Upvotes: 0
Views: 978
Reputation: 158
I would personally use .getTime()
method adding some kind of basic operation, such a pseudo-aleatory number generation added to the returned quantity in milliseconds. Simply because a millisecond is not 100% a reliable output, as Dan Pichelman said, "You'd be surprised how much you can do in a millisecond these days".
Upvotes: 0
Reputation: 863
As you stated, the chance of getting back the same uuid is small - but not impossible. There is no real need to use valueOf instead of getTime. Also there are way better algorithms for generating UUIDS see https://github.com/pnegri/uuid-js for well tested implementations which are also time based.
Upvotes: 1