I need to generate unique id numbers on the fly using javascript. In the past, I've done this by creating a number using time. The number would be made up of the four digit year, two digit month, two digit day, two digit hour, two digit minute, two digit second, and three digit millisecond. So it would look something like this: 20111104103912732 ... this would give enough certainty of a unique number for my purposes.
It's been a while since I've done this and I don't have the code anymore. Anyone have the code to do this, or have a better suggestion for generating a unique ID?
Posting this code snippet here for my own future reference (not guaranteed but satisfactory "unique" enough):
If you just want a unique-ish number, then
would get you a simple number. But if you need the readable version, you're in for a bit of processing:
This performs faster than creating a
Date
instance, uses less code and will always produce a unique number (locally):jsfiddle: http://jsfiddle.net/j8aLocan/
I've released this on Bower and npm: https://github.com/stevenvachon/unique-number
You could also use something more elaborate such as cuid, puid or shortid to generate a non-number.
This also should do:
This creates an almost guaranteed unique 32 character key client side, if you want just numbers change the "chars" var.
https://jsfiddle.net/j0evrdf1/1/
Assumed that the solution proposed by @abarber it's a good solution because uses
(new Date()).getTime()
so it has a windows of milliseconds and sum atick
in case of collisions in this interval, we could consider to use built-in as we can clearly see here in action:Fist we can see here how there can be collisions in the 1/1000 window frame using
(new Date()).getTime()
:Second we try the proposed solution that avoid collisions in the 1/1000 window:
That said we could consider to use functions like the node
process.nextTick
that is called in the event loop as a singletick
and it's well explained here. Of course in the browser there is noprocess.nextTick
so we have to figure how how to do that. This implementation will install anextTick
function in the browser using the most closer functions to the I/O in the browser that aresetTimeout(fnc,0)
,setImmediate(fnc)
,window.requestAnimationFrame
. As suggested here we could add thewindow.postMessage
, but I leave this to the reader since it needs aaddEventListener
as well. I have modified the original module versions to keep it simpler here:So we have in the 1/1000 window: