简体   繁体   中英

Javascript call only once a child function with setInterval()

I want to call myfun1 only once with setInterval. I want to avoid using a global variable. Read this but it does not work (just calls the function every 2000 ms). Naturally I need to call main() every 2000 ms.

(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);

Use a flag :

(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);​

The callItOnce function you wrote should work. You just need to declare the function outside the setInterval call. Otherwise it gets redefined each time.

(function () {

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

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

myfun1 = callItOnce(myfun1);

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

setInterval(main, 2000);

}());

One easy way to work around this is to use a variable on the function itself.

function myFunc1(){

if(arguments.callee.done){return;}


arguments.callee.done = true;    

}

This way the "done" variable on the method myFunc1 would make sure the method is executed only once.

setInterval returns a value that you can pass to clearInterval to stop the callback from being called.

var i = 0;
var timeout_id = setTimeout(function(){
    console.log(i);
    if(i >= 5){ clearTimeout(timeout_id) }
    i++;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM