zoukankan      html  css  js  c++  java
  • 只执行一次的js 函数。

    function runOnce(fn, context) { //控制让函数只触发一次
        return function () {
            try {
                fn.apply(context || this, arguments);
            }
            catch (e) {
                console.error(e);//一般可以注释掉这行
            }
            finally {
                fn = null;
            }
        }
    }
     
    // Usage 1:
    var a = 0;
    var canOnlyFireOnce = runOnce(function () {
        a++;
        console.log(a);
    });
     
    canOnlyFireOnce(); //1
    canOnlyFireOnce(); // nothing
    canOnlyFireOnce(); // nothing
     
    // Usage 2:
    var name = "张三";
    var canOnlyFireOnce = runOnce(function () {
        console.log("你好" + this.name);
    });
    canOnlyFireOnce(); //你好张三
    canOnlyFireOnce(); // nothing
     
    // Usage 3:
    var obj = {name: "天涯孤雁", age: 24};
    var canOnlyFireOnce = runOnce(function () {
        console.log("你好" + this.name);
    }, obj);
    canOnlyFireOnce(); //你好天
    canOnlyFireOnce(); // nothing

    因为返回函数执行一次后,fn = null将其设置未null,所以后面就不会执行了。

    方法2:

    function once(fn, context) { 
        var result;
     
        return function() { 
            if(fn) {
                result = fn.apply(context || this, arguments);
                fn = null;
            }
     
            return result;
        };
    }
     
    // Usage
    var canOnlyFireOnce = once(function() {
        console.log('Fired!');
    });
     
    canOnlyFireOnce(); // "Fired!"
    canOnlyFireOnce(); // nothing
  • 相关阅读:
    ubuntu 安裝QQ ,WEIXIN,百度WP等
    深度学习基础--Bottleneck(瓶颈) Architectures
    sql 函数
    线性回归
    二元逻辑回归
    参数检验
    DrawFrameControl 绘制标准控件
    SetProcessWorkingSetSize 降低程序运行内存
    【转载】VC IME 通信
    【转载】EmptyWorkingSet 程序运行内存整清理
  • 原文地址:https://www.cnblogs.com/wennice/p/7383796.html
Copyright © 2011-2022 走看看