自调用函数中递归函数的 setTimeout() [英] setTimeout() on recursive function within a self invoking function

查看:38
本文介绍了自调用函数中递归函数的 setTimeout()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的代码作为自调用匿名函数来分发,正如我看到的许多人所做的那样.此外,在我的代码中,我必须监视另一个库的加载情况,以便在可用时使用它.

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

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

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

推荐答案

change 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.

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

这篇关于自调用函数中递归函数的 setTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆