Create a unique number with javascript time

后端 未结 30 3071
生来不讨喜
生来不讨喜 2020-12-02 08:31

I need to generate unique id numbers on the fly using javascript. In the past, I\'ve done this by creating a number using time. The number would be made up of the four digi

30条回答
  •  北海茫月
    2020-12-02 08:59

    Assumed that the solution proposed by @abarber it's a good solution because uses (new Date()).getTime() so it has a windows of milliseconds and sum a tick in case of collisions in this interval, we could consider to use built-in as we can clearly see here in action:

    Fist we can see here how there can be collisions in the 1/1000 window frame using (new Date()).getTime():

    console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
    VM1155:1 1469615396590
    VM1155:1 1469615396591
    console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
    VM1156:1 1469615398845
    VM1156:1 1469615398846
    console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
    VM1158:1 1469615403045
    VM1158:1 1469615403045
    

    Second we try the proposed solution that avoid collisions in the 1/1000 window:

    console.log( window.mwUnique.getUniqueID() ); console.log( window.mwUnique.getUniqueID() ); 
    VM1159:1 14696154132130
    VM1159:1 14696154132131
    

    That said we could consider to use functions like the node process.nextTick that is called in the event loop as a single tick and it's well explained here. Of course in the browser there is no process.nextTick so we have to figure how how to do that. This implementation will install a nextTick function in the browser using the most closer functions to the I/O in the browser that are setTimeout(fnc,0), setImmediate(fnc), window.requestAnimationFrame. As suggested here we could add the window.postMessage, but I leave this to the reader since it needs a addEventListener as well. I have modified the original module versions to keep it simpler here:

    getUniqueID = (c => {
     if(typeof(nextTick)=='undefined')
    nextTick = (function(window, prefixes, i, p, fnc) {
        while (!fnc && i < prefixes.length) {
            fnc = window[prefixes[i++] + 'equestAnimationFrame'];
        }
        return (fnc && fnc.bind(window)) || window.setImmediate || function(fnc) {window.setTimeout(fnc, 0);};
    })(window, 'r webkitR mozR msR oR'.split(' '), 0);
     nextTick(() => {
       return c( (new Date()).getTime() )  
     })
    })
    

    So we have in the 1/1000 window:

    getUniqueID(function(c) { console.log(c); });getUniqueID(function(c) { console.log(c); });
    undefined
    VM1160:1 1469615416965
    VM1160:1 1469615416966
    

提交回复
热议问题