Skip to content

Instantly share code, notes, and snippets.

@djsd123
Created July 18, 2022 14:08
Show Gist options
  • Save djsd123/dd140f62aaa0c609f050e00ebf919e11 to your computer and use it in GitHub Desktop.
Save djsd123/dd140f62aaa0c609f050e00ebf919e11 to your computer and use it in GitHub Desktop.
A Function in Typescript/Javascript that can only be called/executed once
/*
I wanted a function that would only work once where all subsequent calls would result in a noop
I stumbled upon this Stackoverflow question: https://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once
However, I found some of the answers difficult to implement in Typescript but on the bright side. I learnt a little about closures.
I added my simple workaround here: https://stackoverflow.com/a/72992927/2719085 and below.
*/
let printName = (name: string) => {
console.log(name)
printName = () => {}
}
printName('Sophia') // Sophia
printName('Nico') // Nothing Happens
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment