5

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?

user2635299
  • 95
  • 1
  • 11
  • 1
    Did you wait more than a millisecond between attempts to generate the numbers? Also, no-repro in Chrome. Which browser are you using? (and it's `valueOf()`, note the upper-case O.) – David Thomas Nov 21 '13 at 12:07
  • If you're trying to create a unique identifier, perhaps http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript might be helful? – Olly Hodgson Nov 21 '13 at 12:11
  • 1
    if you need unique number - try to use global counter, what incremented after each call. This save you from issues as above and reduce javascript – Igor Benikov Nov 21 '13 at 12:15
  • @ David Thomas No.In that case i should go with some other method to generate uniquely?.Chrome browser – user2635299 Nov 21 '13 at 12:17

3 Answers3

11

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    Will i be able to get back time from the timestamp generated using the method as you said above? – user2635299 Nov 21 '13 at 12:23
  • 1
    @user2635299 Yes. The value returned from `new Date().getTime()` is an integer (i.e. fractionless number), while the result of `Math.random()` is always a real number between 0 and 1, excluding 1. So, just discard the fraction (e.g. using `Math.floor()`) and then you have the numeric timestamp that can be used to construct the `Date` object again (using the [Date's `setTime` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime)). – Rob W Nov 21 '13 at 12:25
1

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.

hgoebl
  • 12,637
  • 9
  • 49
  • 72
0

example.Even performance.now() sometimes don't give unique numbers. You have to make your own system to generate it. Something like make a counter and increase it by 1 each time when it is accessed.

Sticky Joe
  • 1
  • 2
  • 1