JS performed only once

1. Closure achieved.

 <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>

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

 

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

 

3. Set a value to control the call back through boolean. flag

 

 <script>
        window.onload = function () {
            var condition = true;

            function once() {
                if (condition) {
                    alert("我被调用");
                    condition = false;
                } else {
                    return;
                }
            }
            once();
            once();
        }
    </script>

Guess you like

Origin www.cnblogs.com/Everythingisobject/p/10950902.html