JavaScript - run once without booleans

后端 未结 9 1199
一个人的身影
一个人的身影 2021-01-30 17:42

Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?

Spe

9条回答
  •  一个人的身影
    2021-01-30 18:06

    A problem with quite a few of these approaches is that they depend on function names to work: Mike's approach will fail if you create a function with "x = function() ..." and Lekensteyn's approach will fail if you set x = useThisFunctionOnce before useThisFunctionOnce is called.

    I would recommend using Russ's closure approach if you want it run right away or the approach taken by Underscore.js if you want to delay execution:

    function once(func) {
        var ran = false, memo;
        return function() {
            if (ran) return memo;
            ran = true;
            return memo = func.apply(this, arguments);
        };
    }
    
    var myFunction = once(function() {
        return new Date().toString();
    });
    
    setInterval(function() {console.log(myFunction());}, 1000);
    

    On the first execution, the inner function is executed and the results are returned. On subsequent runs, the original result object is returned.

提交回复
热议问题