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 yourfunc
. When the loop is done,i
is 8 (timings.length
), which doesn't exist in the array.You need to do something like this:
When your function gets called by
setTimeout
sometime in the future, the value ofi
has already been incremented to the end of it's range by thefor
loop soconsole.log(timings[i]);
reportsundefined
.To use
i
in that function, you need to capture it in a function closure. There are several ways to do that. I would suggest using a self-executing function to capture the value ofi
like this:As a bit of explanation for who this works:
i
is passed to the self-executing function as the first argument to that function. That first argument is namedindex
and gets frozen with each invocation of the self-executing function so thefor
loop won't cause it to change before thesetTimeout
callback is executed. So, referencingindex
inside of the self-executing function will get the correct value of the array index for eachsetTimeout
callback.This is a usual problem when you work with
setTimeout
orsetInterval
callbacks. You should pass thei
value to the function:DEMO: http://jsfiddle.net/r56wu8es/