I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc..
The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
If ID's are generated more than 1 millisecond apart, they are 100% unique.
If two ID's are generated at shorter intervals, and assuming that the random method is truly random, this would generate ID's that are 99.99999999999999% likely to be globally unique (collision in 1 of 10^15)
You can increase this number by adding more digits, but to generate 100% unique ID's you will need to use a global counter.
There is a jQuery plugin that handles Guid's nicely @ http://plugins.jquery.com/project/GUID_Helper
Returns value of internal Guid. If no guid has been specified, returns a new one (value is then stored internally).
Returns a new Guid and sets it's value internally.
Returns an empty Guid 00000000-0000-0000-0000-000000000000.
Returns boolean. True if empty/undefined/blank/null.
Returns boolean. True valid guid, false if not.
Retrns Guid. Sets Guid to user specified Guid, if invalid, returns an empty guid.
There have been a couple attempts at this. The question is: do you want actual GUIDs, or just random numbers that look like GUIDs? It's easy enough to generate random numbers.
However, note that such values are not genuine GUIDs.
Note: the provided code snippet does not follow RFC4122 which requires that the version (
4
) has to be integrated into the generated output string. Do not use this answer if you need compliant GUIDs.Use:
Demo:
A web service would be useful.
Quick Google found: http://www.hoskinson.net/GuidGenerator/
Can't vouch for this implementation, but SOMEONE must publish a bonafide GUID generator.
With such a web service, you could develop a REST web interface that consumes the GUID web service, and serves it through AJAX to javascript in a browser.
I really like how clean Broofa's answer is, but it's unfortunate that poor implementations of
Math.random
leave the chance for collision.Here's a similar RFC4122 version 4 compliant solution that solves that issue by offsetting the first 13 hex numbers by a hex portion of the timestamp. That way, even if
Math.random
is on the same seed, both clients would have to generate the UUID at the exact same millisecond (or 10,000+ years later) to get the same UUID:Here's a fiddle to test.
Here's some code based on RFC 4122, section 4.4 (Algorithms for Creating a UUID from Truly Random or Pseudo-Random Number).