12/19/2014

Minimal Download Strategy and window.setTimeout issue

Sometimes developers from Microsoft create mysterious things...
In two words the issue with setTimeout looks like that.

There is a standard function window.setTimeout. You can provide the function to call, the interval in milliseconds to wait and some additional arguments to be applied to the function. For example:
setTimeout(function(firstName, lastName) {
  alert(firstName + ' ' + lastName);
}, 1000, 'Alex', 'Terentiev');
And that code works fine if the Minimal Download Strategy is deactivated. But if it is activated you'll see "undefined undefined" in the alert window.
It is so because of the override in the start.js file:
window.setTimeout = function() {
  var b;
  if (arguments.length > 1 && "function" == typeof arguments[0]) {
    var c = arguments[0];
    arguments[0] = function() {
      c();
      if ("undefined" != typeof b) {
        var d = Array.indexOf(a._timeoutArray, b);
        -1 != d && a._timeoutArray.splice(d, 1)
      }
    }
  }
  if ("function" == typeof e)
    b = e.apply(window, arguments);
  else
    b = e(arguments[0], arguments[1]);
  "undefined" != typeof b && a._timeoutArray.push(b);
  return b
}
The function you're trying to call is stored in variable c. And it is calling just like c() which means that it will not have any arguments you were passing to setTimeout.
It is just awesome!
You can fix that issue by adding some code to the callee function (the function you're calling after timeout):
if (!arguments.length) {
  var caller = arguments.callee.caller;

  if (caller) {
    var callerArgs = caller.arguments;
    // get arguments from callerArgs
  }
}
Have fun!

No comments:

Post a Comment