Gearside Design

JavaScript Once function for one-time-only events

There are times in JavaScript when you need to call a function one time and then never again for that page. Here is a flexible way of doing so!

This method does not require the function being called to be declared a certain way because it is used when calling a function- not when defining a function. That also means it can be used with any existing functions- including those within external libraries.

Another benefit of the flexibility here is that it can be used with a boolean return by not referencing another function.

How It Works

Call the function that should only run one time by wrapping it inside of this once() function. Be sure to call it without the self-executing parenthesis.

Any parameters that need to be passed should be entered in the second “args” array.

Finally, use the third parameter to pass a unique string. This string allows functions with different names to be tied to the same unique strings. If a function and arguments are not sent (so, only passing a unique string), this function will return a boolean true/false.

The Function