Generating unique Ids based on the current milliseconds
For simple use-cases generating id based on current milliseconds is the easiest way to get unique Ids. But while generating we need to take care of one race condition i.e what if the generate Id method called more than once within a millisecond. Following is sample Javascript code that shows generating Id based on current milliseconds also taking care of duplicates in case of being called in the same millisecond.
var lastId = 0;
function getId(){
var currentId = new Date().getTime();
if (lastId == currentId) {
currentId++;
}
lastId = currentId;
return lastId;
}
Note: This id generation strategy can be used in low volume scenarios only with occasional bursts. But if you are load is close to or more than 86 Million per day (milliseconds per day) then you should avoid this strategy.