Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript timestamp number is not unique

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?

like image 616
user2635299 Avatar asked Nov 21 '13 12:11

user2635299


People also ask

What is a valid timestamp?

Every valid number is a timestamp. If it satisfies the condition of valid integer number then it will also satisfy the condition of the valid timestamp. Timestamp = The number of milliseconds since 1970/01/01.

How do you create a timestamp in JavaScript?

How to Use valueOf() to Generate Timestamps in JS. Just like the getTime() method, we have to attach the valueOf() method to a new Date() object in order to generate a Unix timestamp. The new Date() object, without getTime() or valueOf() , returns the information about your current time.

What is timestamp JavaScript?

A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.


2 Answers

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.

like image 144
Rob W Avatar answered Oct 06 '22 17:10

Rob W


On Windows the resolution of the timer is about 10.5 ms. So you have chances of getting the same value even few milliseconds later. There are better timers of course, but AFAIK they are not available to JavaScript.

like image 42
hgoebl Avatar answered Oct 06 '22 19:10

hgoebl