Languages
[Edit]
EN

JavaScript - generate unique id (useful in web browser)

2 points
Created by:
Root-ssh
177560

In this short article, we would like to show how to generate a unique id that can be used on UI.

The below solution to provide unique IDs that is created using incremented counter + current time + random number.

The idea bases on:

  • incremented counter is always unique per loaded webpage  - refresh / reload causes reset,
  • current time provides unique time between webpage reloading / refreshing - only incorrect time in the operating system can duplicate values,
  • random number increases the probability that generated ID will be unique.

Note: the way how to generate UUID was described in this article.

Advantages: the presented solution has very good performance - better than UUID implementation presented in this article.

Quick solution:

// ONLINE-RUNNER:browser;

var counter = 0;

function renderCounter(base) {
    var value = (++counter);
    return value.toString(base || 10);
}

function renderTime(base) {
	var value = Date.now();
	return value.toString(base || 10);
}

function renderRandom(base) {
    var value = Math.floor(1e+16 + 9e+16 * Math.random());
	return value.toString(base || 10);
}

function generateId(base, separator) {
    if (separator == null) {
        separator = '-';
    }
	return renderCounter(base) + separator + renderTime(base) + separator + renderRandom(base);
}


// Usage example:

console.log(generateId(10));
console.log(generateId(16));
console.log(generateId(32));

 

ES6+ example

// ONLINE-RUNNER:browser;

let counter = 0;

const renderCounter = (base = 10) => {
    const value = (++counter);
    return value.toString(base);
};

const renderTime = (base = 10) => {
	const value = Date.now();
	return value.toString(base);
};

const renderRandom = (base = 10) => {
    const value = Math.floor(1e+16 + 9e+16 * Math.random());
	return value.toString(base);
};

const generateId = (base = 10, separator = '-') => {
	return renderCounter(base) + separator + renderTime(base) + separator + renderRandom(base);
};


// Usage example:

console.log(generateId(10));
console.log(generateId(16));
console.log(generateId(32));

 

See also

  1. JavaScript - UUID function in Vanilla JS 

Alternative titles

  1. JavaScript - generate random id (useful in web browser)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join