IE parameters get undefined when using them in set

2020-02-28 18:15发布

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/

3条回答
别忘想泡老子
2楼-- · 2020-02-28 18:49

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;
}
查看更多
Viruses.
3楼-- · 2020-02-28 18:51
setTimeout(function(){myFunction(myParam, tries);}, 50);

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

查看更多
走好不送
4楼-- · 2020-02-28 18:55

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

You need to wrap the function in a function which requires no arguments:

function myFunction(myParam, tries){
  if (typeof tries == "undefined"){
    tries = 0;
  }
  tries++;
  if (tries < 2){
    setTimeout(function() {
         myFunction(myParam, tries);
    }, 50);

  }
}

myFunction("something");
查看更多
登录 后发表回答