Home > Web Front-end > JS Tutorial > Three common methods to make functions in js have only one valid call

Three common methods to make functions in js have only one valid call

PHPz
Release: 2018-10-10 16:00:16
forward
1846 people have browsed it

How to make a function in js only executed once? We sometimes have this requirement, that is, to execute a function only once, and the second call will not return any valuable value or report an error. The following will show the methods used through three small demos, as personal notes.

1. Implemented through closure.

 <script>
        window.onload = function () {            function once(fn) { 
                var result;            
              return  function() { 
                    if(fn) {
                        result = fn.apply(this, arguments);
                        fn = null;
                    }                    return result;
                };
            }            
            var callOnce = once(function() {
                console.log('javascript');
            });
            
            callOnce(); // javascript
            callOnce(); // null        }    </script>
Copy after login

2. After the first call, leave the func function value empty. func= function(){};

  <script>        var func = function () {
            alert("正常调用");
            func= function(){};
        }
        func();
        func();    </script>
Copy after login

3. Set a value and use boolean to control subsequent calls.

 <script>
        window.onload = function () {            var flag = true;            function once() {                if (flag) {
                    alert("我被调用");
                    flag = false;
                } else {                    return;
                }
            }
            once();
            once();
        }    </script>
Copy after login

For more related tutorials, please visit JavaScript Video Tutorial

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template