Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-22 23:14:29
Original
951 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!