Javascript timestamp number is not unique

前端 未结 2 733
一整个雨季
一整个雨季 2020-12-21 03:17

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 mi

相关标签:
2条回答
  • 2020-12-21 03:29

    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.

    0 讨论(0)
  • 2020-12-21 03:31

    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.

    0 讨论(0)
提交回复
热议问题