setTimeout() on recursive function within a self i

2019-02-05 07:17发布

I want to distribute my code as a self-envoking anonymous functions, as I see many do. Also, within my code I have to monitor for another lib loading, so I can use it when it's available.

(function(window, document, undefined) {
  staffHappens();
  var initMyLib = function() {
    if (typeof(myLib) == 'undefined') {
      setTimeout("initMyLib()", 50);
    } else {
      useMyLib();
    }
  }
  moreStaffHappens();
  initMyLib(); //-> initMyLib is undefined
})(this, document);

How can this error occur? Should initMyLib be inside the scope of the enclosing (self-envoking) function?

3条回答
劫难
2楼-- · 2019-02-05 07:42

change setTimeout("initMyLib()", 50); to setTimeout(initMyLib, 50);

When you pass a string as an argument it will try to evaluate it when the timeout is fired, but it will run in the global scope. And your method does not exist in the global scope.


Demo at http://jsfiddle.net/gaby/zVr7L/

查看更多
戒情不戒烟
3楼-- · 2019-02-05 07:43

Try reading this answer for some clues: recursive function vs setInterval vs setTimeout javascript

This is the code sample from that answer:

/*
this will obviously crash... and all recursion is at risk of running out of call stack and breaking your page...

function recursion(c){
    c = c || 0;
    console.log(c++);
    recursion(c);
}
recursion();

*/

// add a setTimeout to reset the call stack and it will run "forever" without breaking your page!
// use chrome's heap snapshot tool to prove it to yourself.  :)

function recursion(c){
    setTimeout(function(c){
        c = c || 0;
        console.log(c++);
        recursion(c);
    },0,c);
}

recursion();

// another approach is to use event handlers, but that ultimately uses more code and more resources
查看更多
Animai°情兽
4楼-- · 2019-02-05 08:00

You could also use a real anonymous function to avoid scoping issues:

(function() {
    if(typeof(myLib) == 'undefined')
        setTimeout(arguments.callee, 50);
    else
        // loaded
})()
查看更多
登录 后发表回答