Categories
JavaScript Answers

How to create a function in JavaScript that can be called only once?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *