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/
You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With