Generating random numbers in JavaScript is really easy. Try to google them; I am pretty sure the most results will show Math.random().

Basically generating a random number in JavaScript looks like this:

1 2 |
// Math.random() creats a floating point number like 0.8556360309012234 console.log('My random number: %f', Math.random()); |

Add a bit more randomness to your number by making it a natural number and adding the current time since 1970/01/01 in milliseconds.

1 |
Math.floor( Math.random() * 1e9 ).toString() + (new Date().getTime()); |

As you can see we cast the natural number to a string before *adding* the current timestamp. It’s more a string concat instead of a mathematical adding. But it makes the result more unique.

In general the result of our random number is good enough to use them as a unique number in the client.

However we have a unique result – it’s not really secure. Math.random() is not desined for cryptographically use. If you want to create more secure numbers you should try window.crypto.

window.crypto is implemented by the most modern browsers. But you should always use feature detection and support a fallback if it’s not supported by the users client.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function createNumber() { var number; try { // If the client supports the more secure crypto lib if (Uint32Array && window.crypto && window.crypto.getRandomValues) { var numbers = new Uint32Array(1); window.crypto.getRandomValues(numbers); number = numbers.length ? (numbers[0] + '') : null; } } catch(e) { // If the browser fucks up ... } finally { // The fallback if (!number) { number = Math.floor( Math.random() * 1e9 ).toString() + (new Date().getTime()); } } return number; }; |

Yep, the result is always returned as a string. Remove the .toString()/” if you need a proper JavaScript number or cast the result at the end.