Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE parameters get undefined when using them in setTimeout [duplicate]

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/

like image 852
Jasper de Vries Avatar asked Sep 13 '12 10:09

Jasper de Vries


People also ask

How do you pass arguments in setTimeout?

You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg.

Does setTimeout block code?

The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);

How many parameters does setTimeout accept?

Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.


1 Answers

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;
}
like image 191
Denys Séguret Avatar answered Nov 02 '22 19:11

Denys Séguret