Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>jQuery.now()</code> isn't supposed to give you a unique number, just a " a number representing the current time" (<a href="http://api.jquery.com/jQuery.now/" rel="nofollow noreferrer">http://api.jquery.com/jQuery.now/</a>). More specifically "the number of milliseconds since 1 January 1970 00:00:00 UTC" (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime</a>).</p> <p>The simplest way to generate a unique identifier depends on the scope the identifier has to be unique in.</p> <p>1: If the identifier just has to be unique within the scope of the function, a counter as suggested by SteveP would probably do the job best.</p> <p>2: If the identifier needs to be unique within the scope of your application - and you do not have the possibility to keep track of the assigned identifiers (as in 1) - your job is more difficult. In real-live applications such a scenario could be tackled by combining the timestamp with a random number, along the lines of</p> <pre><code>var identifier = $.now() + "_" + Math.round(Math.random() * 1e10) </code></pre> <p>This approach doesn't guarantee for true uniqueness of <code>identifier</code> though since <code>Math.round(Math.random() * 1e10)</code> could return the same value twice in one millisecond. Depending on how often you generate a string like this, it will be still pretty unlikely you end up with the same string twice.</p> <p>3: If you however aim for "uniqueness across space and time", you could get inspiration from <a href="http://www.ietf.org/rfc/rfc4122.txt" rel="nofollow noreferrer">http://www.ietf.org/rfc/rfc4122.txt</a></p> <p>It should be noted that pure Javascript implementations like <a href="https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript#answer-2117523">Create GUID / UUID in JavaScript?</a> only work with random numbers as well and will thus not generate <em>truly</em> unique identifiers. For a <em>truly</em> unique identifier across space and time a <em>truly</em> unique element such as a mac-address has to be used as part of the identifier.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload