简体   繁体   中英

How can I call an anonymous function from inside itself in JavaScript?

Is it possible to re-run the function 'check' without calling check() in the else statement? Maybe call itself somehow?

If I have multiple instances of this function, they end up calling each other, unless I change it to check1, check2, etc.. While this is prob. a performance killer, I was just trying it out for a prototype app.

(function check () {
  if (typeof foo !='undefined') {
    // do stuff
  } else {
    console.log("Failed to load, trying again");
    setTimeout(function(){ check(); }, 10);
  }
})();

Well, you could use arguments.callee to call it, but it's a bad idea, a performance hit, and it isn't valid in strict mode.

What you've quoted is valid JavaScript and should not make check call another check function if you have one alongside it. Sadly, though, it will in IE8 and earlier because they quite incorrectly leak the name check to the surrounding scope (named function expressions do not add the function name to the surrounding scope like function declarations do — except on IE8 and earlier [and that's not all they get wrong with them]).

So the solution is to use an anonymous function to hide a named one:

(function() {
    // A check function
    check();
    function check () {
      if (typeof foo !='undefined') {
        // do stuff
      } else {
        console.log("Failed to load, trying again");
        setTimeout(function(){ check(); }, 10);
      }
    }
})();
(function() {
    // A complete different one
    check();
    function check () {
      if (typeof foo !='undefined') {
        // do other stuff
      } else {
        console.log("Failed to load, trying again");
        setTimeout(function(){ check(); }, 10);
      }
    }
})();

How about using an interval instead removing the need to call itself, as this will be done automatically until you clear the interval:

(function(){
   var interval = setInterval(function(){
      if(typeof foo != 'undefined'){
         clearInterval(interval);
         // do stuff
      }else{
         console.log("Failed to load, trying again");
      }
   },10)
})();

Why not do something like this instead:

var inter;

function check() {
    if (typeof foo !== 'undefined') {
        clearInterval(inter);
        // do stuff
    } else {
        console.log("Failed to load, trying again");
    }
}
inter = setInterval(check, 10);

It's not a drop in replacement, but I think it's better style.

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