Javascript只调用一次具有setInterval()的子函数

jac*_*des 0 javascript jquery

我想用setInterval只调用一次myfun1.我想避免使用全局变量.读取但它不起作用(只需每2000毫秒调用一次该函数).当然我需要每2000毫秒调用main().

(function($){         
    setinterval(main,2000);  

     function main (){            
        if(/*condition*/) return;

        function callItOnce(fn) {
            var called = false;
            return function() {
                if (!called) {
                    called = true;
                    return fn();
                }
                return;
            }
        }

        myfun1 = callITOnce(myfun1);
        myfun1();

        function myfun1(){/*code*/};
        function myfun2(){/*code*/};
        function myfun3(){/*code*/};
})(jquery);
Run Code Online (Sandbox Code Playgroud)

ade*_*neo 5

使用标志:

(function($){ 
    var timer = setInterval(main,2000), ran=true;

    function main() {
        if(/*condition*/) return;

        if (ran) { //runs when ran=true, which is only the first time
            myfun1();
            ran = false;  //since it's set to false here
        }

        function myfun1(){/*code*/};
        function myfun2(){/*code*/};
        function myfun3(){/*code*/};

})(jquery);?
Run Code Online (Sandbox Code Playgroud)