javascript 自调用函数中递归函数的 setTimeout()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8821765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:41:05  来源:igfitidea点击:

setTimeout() on recursive function within a self invoking function

javascriptclosuressettimeoutanonymous-function

提问by user967722

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?

这个错误怎么会发生?initMyLib 是否应该在封闭(自调用)函数的范围内?

回答by Gabriele Petrioli

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

更改setTimeout("initMyLib()", 50);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 athttp://jsfiddle.net/gaby/zVr7L/

演示在http://jsfiddle.net/gaby/zVr7L/

回答by georg

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

您还可以使用真正的匿名函数来避免范围问题:

(function() {
    if(typeof(myLib) == 'undefined')
        setTimeout(arguments.callee, 50);
    else
        // loaded
})()

回答by ire-a

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

尝试阅读此答案以获取一些线索: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