I need a unique number to be generated to be used in my code.I use
var id = new Date().valueOf()
I know the above returns the number of milliseconds. But the values are not unique.For example :1385035174752.This number is generated twice or more than that.
My question is Why is it not unique? and how do i get unique number from current date/time?
Advertisement
Answer
If you need uniqueness, use Math.random()
, and not any of the Date()
APIs.
Math.random
returns an integer between and including 0 and 1. If you really want an semi-unique number based on the current time, you can combine the Date
API with Math.random
. For example:
var id = new Date().getTime() + Math.random();
In modern browsers, you can also use performance.now()
. This API guarantees that every new call’s return value is unique.