6

可能重复:
setTimeout Internet Explorer

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");

有没有办法解决这个问题?

http://fiddle.jshell.net/rH3gx/

4

3 回答 3

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;
}
于 2012-09-13T10:49:25.787 回答
8

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");
于 2012-09-13T10:52:32.957 回答
1
setTimeout(function(){myFunction(myParam, tries);}, 50);

http://fiddle.jshell.net/rH3gx/1/

于 2012-09-13T10:53:44.693 回答