在setTimeout中使用IE参数时,IE参数未定义 [英] IE parameters get undefined when using them in setTimeout

查看:272
本文介绍了在setTimeout中使用IE参数时,IE参数未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

setTimeout Internet Explorer

我在这里遗漏了什么或是否有问题将函数参数传递给 setTimeout <时的Internet Explorer / code> 调用相同的函数?

Am I missing something here or is there a problem in Internet Explorer when passing function parameters to a setTimeout calling the same function?

这将在Internet Explorer中永久运行:

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 :


如果你需要将一个参数传递给你的回调函数,但需要它
在Internet Explorer中工作,它不支持发送额外的
参数(既不用setTimeout()也不用setInterval())你可以
包含这个IE特定的兼容性代码,它将启用
HTML5标准参数在该浏览器中为
两个计时器通过功能只需将其插入脚本的开头。

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;
}

这篇关于在setTimeout中使用IE参数时,IE参数未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆