Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Created April 11, 2021 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconifyit/b7b131208bf9534181ae7959070746af to your computer and use it in GitHub Desktop.
Save iconifyit/b7b131208bf9534181ae7959070746af to your computer and use it in GitHub Desktop.
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