Generating element IDs with JavaScript and counters
The code that I posted in my previous post on creating a unique ID in JavaScript is fairly similar to code that's all over the internet and seemed like it should work. And to be fair, it did work, although with one major problem. If the code runs too quickly it's possible for two elements to have the same "unique" id.
What I came up with instead was using a counter to keep track of the last ID given and increment it each time.
JavaScript:
-
var uniqueCounter=0;
-
function generateUniqueID()
-
{
-
uniqueCounter++;
-
return uniqueCounter.toString(16);
-
}
I wanted to have the number returned as hex which is why the .toString(16) is on the end. No real reason, it just seemed like the right thing to do. If you just want a number you can use this.
JavaScript:
-
var uniqueCounter=0;
-
function generateUniqueID()
-
{
-
return uniqueCounter++;
-
}
Question, Comments...
Do you have more questions. Please either leave a comment below or join us in our new forum.
Maybe it’s the way to do the same thing you posted before but without bug.. ?
var uniqueCounter=0;
function uid(){
uniqueCounter++;
var newDate = new Date;
return newDate.getTime() + uniqueCounter++;
}
I didn’t really need it to be unique overall, just unique to the page. So a global counter worked for me. I did actually play with the Date object originally but found it was a little unnecessary for my needs.
Like the idea though. Your code is simpler than what I came up with originally.
So what happends if the function is called from two different places at the exact same time?
Two different places? Every time it’s called it’s incremented for that visitor. It’s building a page for that user with a unique id so it doesn’t matter if two visitors have the same id.
I think Flemming is referring to the situation where the same script is running in 2 separate browsers at the same time, communicating the id to a common server as a unique id. In that case, a duplicate is possible, right?