lundi 15 janvier 2018

Is this JS Unique ID Generator Unreliable? (Getting collisions)

I am using the following JS function to generate unique IDs, which I got from another StackOverflow thread:

function generateUniqueID() {
    return Math.round(new Date().getTime() + (Math.random() * 100));
}

I see that it combines the current Date/Time with an additional Randomizer.

Nonetheless, I verified that I'm getting collisions on every 4th or 5th operation of quickly adding items with IDs.

enter image description here

The function is called inside a JS loop to generate IDs from the list of current elements.

    jQuery.each(mainEvents, function(index, item) {
        // ...
        // Generate gaps
        gapEvents.push({"gapEventID" : "event-GAP" + generateUniqueID(), 
                                "other" : other });        
}

Is this function unreliable? Could it allow collisions in quick JS loop iterations?




Aucun commentaire:

Enregistrer un commentaire