将参数传递给setTimeout的闭包 [英] Passing parameters into a closure for setTimeout

查看:148
本文介绍了将参数传递给setTimeout的闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,即我的应用程式位于iFrame中,而且正从外部网域呼​​叫。 IE9不会触发加载事件,当iframe加载正确,所以我想我卡住使用setTimeout轮询页面。



无论如何,我想看看什么时间通常需要我的setTimeout完成,所以我想能够记录setTimeout从我的回调的触发延迟,但我不知道如何传递上下文到它,所以我可以记录它。

  App.readyIE9 = function(){
var timings = [1,250,500,750,1000,1500,2000,3000];
for(var i = 0; i< timings.length; i ++){
var func = function(){
if(App.ready_loaded)return;
console.log(timings [i]);
App.readyCallBack();
};
setTimeout(func,timings [i]);
}
};

我在IE9的控制台中收到LOG:undefined。


$ b $

解决方案

这是因为您不会在 func 中关闭 i 的值。当循环完成时, i 是8( timings.length ),在数组中不存在。



您需要这样做:

  App.readyIE9 = function(){
var timings = [1,250,500,750,1000,1500,2000,3000];
for(var i = 0; i< timings.length; i ++){
var func = function(x){
return function(){
if ready_loaded)return;
console.log(timings [x]);
App.readyCallBack();
};
};
setTimeout(func(i),timings [i]);
}
};


I've run into an issue where my app lives in an iframe and it's being called from an external domain. IE9 won't fire the load event when the iframe loads properly so I think I'm stuck using setTimeout to poll the page.

Anyway, I want to see what duration is generally needed for my setTimeout to complete, so I wanted to be able to log the delay the setTimeout fires from my callback, but I'm not sure how to pass that context into it so I can log it.

App.readyIE9 = function() {
  var timings = [1,250,500,750,1000,1500,2000,3000];    
  for(var i = 0; i < timings.length; i++) {
    var func = function() {
    if(App.ready_loaded) return;
      console.log(timings[i]);
      App.readyCallBack();
    };
    setTimeout(func,timings[i]);
  }
};

I keep getting LOG: undefined in IE9's console.

What's the proper method to accomplish this?

Thanks

解决方案

This is happening because you are not closing around the value of i in your func. When the loop is done, i is 8 (timings.length), which doesn't exist in the array.

You need to do something like this:

App.readyIE9 = function() {
  var timings = [1,250,500,750,1000,1500,2000,3000];    
  for(var i = 0; i < timings.length; i++) {
    var func = function(x) {
      return function(){
          if(App.ready_loaded) return;
          console.log(timings[x]);
          App.readyCallBack();
      };
    };
    setTimeout(func(i),timings[i]);
  }
};

这篇关于将参数传递给setTimeout的闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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