简体   繁体   中英

Generating a unique ID in javascript. Understanding this code

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?

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.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM