Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript singleton implementation
/*
* The instance symbol should be defined in the scope
* in which you want the singleton to exist. This does
* not necessarily mean globally. Just within your
* outermost execution context.
*/
let instance;
const Singleton = (() => {
const createInstance = () => {
const ts = String(new Date().getTime());
console.log('Calling createInstance', ts)
return `Instance timestamp : ${ts}`
};
return {
getInstance: () => {
if (instance === undefined) {
instance = createInstance();
}
return instance;
},
};
})();
// This part just tests the above to verify it is a true singleton.
let counter = 0;
let tid = setInterval(() => {
console.log( Singleton.getInstance() )
counter++
if (counter > 5) clearInterval(tid)
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment