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

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

问题描述

我想将我的代码分发为一个自我嗅探的匿名函数,我看到很多。另外,在我的代码中,我必须监控另一个lib加载,所以我可以使用它时,它可用。

 窗口,文档,未定义){
staffHappens();
var initMyLib = function(){
if(typeof(myLib)=='undefined'){
setTimeout initMyLib();
initMyLib(); / /
initMyLib();
initMyLib / - > initMyLib未定义
})(this,document);

此错误如何发生? initMyLib是否应该在封闭(self-envoking)函数的范围内?

解决方案 initMyLib(),50); 到 setTimeout(initMyLib,50);



当你传递一个字符串作为参数时,它将尝试在超时触发时进行评估,但它将在全局范围内运行。

http://jsfiddle.net/gaby/zVr7L/ =nofollow> http://jsfiddle.net/gaby/zVr7L/


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?

解决方案

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/

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

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