Jas*_*ies 6 javascript internet-explorer settimeout
我在这里遗漏了什么或者在将函数参数传递给setTimeout调用相同函数时Internet Explorer中是否存在问题?
这将在Internet Explorer中永久运行:
function myFunction(myParam, tries){
if (typeof tries == "undefined"){
tries = 0;
}
tries++;
if (tries < 2){
setTimeout(myFunction, 50, myParam, tries);
}
}
myFunction("something");
Run Code Online (Sandbox Code Playgroud)
有办法解决这个问题吗?
Den*_*ret 15
解释和解决方案在MDN中:
如果你需要将一个参数传递给你的回调函数,但需要它在Internet Explorer中工作,它不支持发送附加参数(setTimeout()或setInterval()),你可以包含这个IE特定的兼容性代码只需在脚本的开头插入,就可以在该浏览器中为两个定时器启用HTML5标准参数通道功能.
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;
}
Run Code Online (Sandbox Code Playgroud)
http://fiddle.jshell.net/rH3gx/2/
您需要将函数包装在不需要参数的函数中:
function myFunction(myParam, tries){
if (typeof tries == "undefined"){
tries = 0;
}
tries++;
if (tries < 2){
setTimeout(function() {
myFunction(myParam, tries);
}, 50);
}
}
myFunction("something");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6082 次 |
| 最近记录: |