Home  >  Article  >  Web Front-end  >  How to Build a Function in JavaScript That Executes Only Once?

How to Build a Function in JavaScript That Executes Only Once?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 23:14:29953browse

How to Build a Function in JavaScript That Executes Only Once?

How to Create a Function in JavaScript that Can Only Execute Once

JavaScript doesn't inherently offer a way to create functions that can only run once. However, there are elegant solutions using closures and third-party libraries.

Closure Method:

A closure creates a private scope that can be accessed by the function it contains. Within this scope, a flag can be set to indicate whether the function has been executed. The following code demonstrates this approach:

<code class="javascript">var something = (function() {
    var executed = false;
    return function() {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();</code>

Calling something() the first time invokes the function and sets executed to true. Subsequent calls will have no effect because executed remains true.

Third-Party Library Method:

Libraries like Underscore and Ramda provide a once() function that wraps a supplied function and ensures it runs only once.

<code class="javascript">// Using Underscore
var one_something = _.once(something);

// Using Ramda
const one_something = R.once(something);</code>

The returned function can be called multiple times, but the underlying function will only run the first time.

Utilities for Creating One-Time Functions:

If you're not using a library, you can create a custom utility function. One approach is:

<code class="javascript">function once(fn, context) { 
    var result;
    return function() { 
        if (fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        }
        return result;
    };
}</code>

This function accepts a function and optionally a context. It returns a function that executes the original function on the first call and returns the result. Subsequent calls have no effect.

The above is the detailed content of How to Build a Function in JavaScript That Executes Only Once?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn