Wednesday, January 9, 2013

Tip: JavaScript getTime cannot guarantee unique numbers generation.

Recently i have been working on a project that uses JavaScript to generate unique identifiers based on the number of items selected by a user. A loop will go through the selected items and use the getTime function to generate an id for each item. Problems could occur when things run on a fast machine, 2 same ids can be used if the difference between the 2 loops are split micro seconds only. The workaround i used is to store the generated ids and compare it with the newly generated id to ensure that the new id is not already used. Another alternative is to use an incremental number in a loop and create a way to keep track it.