Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate unique ids client-side (with Javascript)

I need to generate unique ids in the browser. Currently, I'm using this:

Math.floor(Math.random() * 10000000000000001)

I'd like to use the current UNIX time ((new Date).getTime()), but I'm worried that if two clients generate ids at the exact same time, they wouldn't be unique.

Can I use the current UNIX time (I'd like to because that way ids would store more information)? If not, what's the best way to do this (maybe UNIX time + 2 random digits?)

like image 487
Tom Lehman Avatar asked Aug 24 '09 05:08

Tom Lehman


3 Answers

you can create a GUID using the following links:

http://softwareas.com/guid0-a-javascript-guid-generator

Create GUID / UUID in JavaScript?

This will maximise your chance of "uniqueness."

Alternatively, if it is a secure page, you can concatenate the date/time with the username to prevent multiple simultaneous generated values.

like image 187
Russell Avatar answered Oct 11 '22 22:10

Russell


https://github.com/uuidjs/uuid provides RFC compliant UUIDs based on either timestamp or random #'s. Single-file with no dependencies, supports timestamp or random #-based UUIDs, uses native APIs for crypto-quality random numbers if available, plus other goodies.

like image 33
broofa Avatar answered Oct 11 '22 21:10

broofa


In modern browser you can use crypto:

var array = new Uint32Array(1);
window.crypto.getRandomValues(array);
console.log(array);
like image 22
Jules Goullee Avatar answered Oct 11 '22 22:10

Jules Goullee