在setTimeout中使用IE参数时,IE参数未定义

时间:2012-09-13 10:47:07

标签: javascript internet-explorer settimeout

  

可能重复:
  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/

3 个答案:

答案 0 :(得分:15)

解释和解决方案是in the 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;
}

答案 1 :(得分:7)

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

答案 2 :(得分:1)

setTimeout(function(){myFunction(myParam, tries);}, 50);

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