This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
setTimeout Internet Explorer
Am I missing something here or is there a problem in Internet Explorer when passing function parameters to a setTimeout
calling the same function?
This will run forever in Internet Explorer:
function myFunction(myParam, tries){
if (typeof tries == "undefined"){
tries = 0;
}
tries++;
if (tries < 2){
setTimeout(myFunction, 50, myParam, tries);
}
}
myFunction("something");
Is there a way to work around that problem?
http://fiddle.jshell.net/rH3gx/
The explanation and solution are in the MDN :
If you need to pass an argument to your callback function, but need it
to work in Internet Explorer, which doesn't support sending additional
parameters (neither with setTimeout() or setInterval()) you can
include this IE-specific compatibility code which will enable the
HTML5 standard parameters passage functionality in that browser for
both timers just by inserting it at the beginning of your scripts.
if (document.all && !window.setTimeout.isPolyfill) {
var __nativeST__ = window.setTimeout;
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeST__(vCallback instanceof Function ? function () {
vCallback.apply(null, aArgs);
} : vCallback, nDelay);
};
window.setTimeout.isPolyfill = true;
}
if (document.all && !window.setInterval.isPolyfill) {
var __nativeSI__ = window.setInterval;
window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeSI__(vCallback instanceof Function ? function () {
vCallback.apply(null, aArgs);
} : vCallback, nDelay);
};
window.setInterval.isPolyfill = true;
}
http://fiddle.jshell.net/rH3gx/2/
You need to wrap the function in a function which requires no arguments:
function myFunction(myParam, tries){
if (typeof tries == "undefined"){
tries = 0;
}
tries++;
if (tries < 2){
setTimeout(function() {
myFunction(myParam, tries);
}, 50);
}
}
myFunction("something");
setTimeout(function(){myFunction(myParam, tries);}, 50);
http://fiddle.jshell.net/rH3gx/1/