Passing parameters to close for setTimeout

I had a problem when my application runs in an iframe and is called from an external domain. IE9 will not fire a load event when the iframe loads correctly, so I think I'm stuck using setTimeout to poll the page.

Anyway, I want to know how long it usually takes to complete my setTimeout, so I wanted to be able to log the delay caused by running setTimeout from my callback, but I'm not sure how to pass this context to it so I can register 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 the IE9 console.

What is the correct method for doing this?

thank

+5
source share
3

, i func. , 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(App.ready_loaded) return;
          console.log(timings[x]);
          App.readyCallBack();
      };
    };
    setTimeout(func(i),timings[i]);
  }
};
+10

setTimeout , i for, console.log(timings[i]); undefined.

i , . . , i :

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

, : i . index , for setTimeout. , index setTimeout.

+10

setTimeout setInterval. i :

var timings = [1, 250, 500, 750, 1000, 1500, 2000, 3000],
    func = function(i) {
        return function() {
            console.log(timings[i]);
        };
    };

for (var i = 0, len = timings.length; i < len; i++) {
    setTimeout(func(i), timings[i]);
}

DEMO: http://jsfiddle.net/r56wu8es/

+3

All Articles