To create a function in JavaScript that can be called only once, we can set a property on the function after it’s executed.
For instance, we write
const myFunc = () => {
if (myFunc.fired) {
return;
}
myFunc.fired = true;
//...
};
to check the myFunc.fired
property is set to true
.
If it is, then we stop running myFunc
with return
.
Otherwise, we set myFunc.fired
to true
and run the rest of the code.
Conclusion
To create a function in JavaScript that can be called only once, we can set a property on the function after it’s executed.