JavaScript: Very simple UID

Developers Kindergarten

As you know there are several portable mechanisms to make unique ID’s in javascript, running inside a browser page. Here is my very simple but still very usable mechanism.
I use the timer ID value, which is returned by setTimeout() calls. Therefore I am able to create a function that is guaranteed to return an integer which is different from any previous or future return values of the same function , while inside the same page session.

Above returns unique integers. Obviously made by some internal counter with an arbitrary base. In my IE8 , I have this :

Is this “unique enough” ? Well, on the level of a page where it is used it is unique enough, indeed. If we want this to be unique enough for (for example) ajax postings to the server, we can simply “adorn” it with some prefix, or suffix. In form of a string made from document.location, or whichever fancy and clever mechanism one prefers.

But still, here is an extremely simple and still perfectly usable heart of the algorithm for generating UID’s in javascript running inside a browser page.

My current UID generator is this:

This is certainly “good enough” as an UID, but not as an GUID, where G stands for “Globaly”. But, for simple scripting inside a single page, this is quite “good enough”. Here is the test and its results :

The test results are :

Here also lies an explanation of why can’t we just use the current time as an uid. Because time resolution is not small enough. In the code above, since test is a quite tight and short loop, getTime(), result is rendered useless as an unique value. The whole loop finished in under one milli second, so all the time values are that same one milli second. They are all the same. Instead, I also used my little timer ID mechanism (and its counter) and, I get true and real UID’s for the current page.