1

I was allways certain that all the additional parameters you pass to setTimeout will be forwarded to the callback:

function say(what) {
  alert(what);
}
setTimeout(say, 500, "Hello world.");

MDN confirms this belief of mine:

var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);

But not so much the actual code:

function reload(cb) {
  var req = new XMLHttpRequest();
  req.open("GET", location.href);
  //Call the callback on request completion
  req.onload = function() {
    console.log("Reloaded, calling callback.");
    if(cb!=null)
      cb();
    else
      console.log("  Callback is null.");
  }
  //Debug info
  console.log("Sending request. Callback: "+cb);
  console.log("   Arguments: "+arguments.length);
  req.send(); 
}
function waitReload() {
  console.log("Reload in 20 ms.");
  //Sending 3 arguments in 20ms
  setTimeout(reload, 20, waitReload, "BLE", "Number 666");
}
waitReload();

jsFiddle

This prints out:

Reload in 20 ms.
Sending request. Callback: undefined
  Arguments: 0
Reloaded, calling callback.
  Callback is null.

No arguments are sent to the callback function. Why? The first code doesn't work either, it alerts undefined.

1 Answers1

0

The parameter syntax is not supported in IE9 and below.

For convinience and cross browser compatibility you should use following syntax, when you need to pass parameters:

setTimeout(function(){myFunction(param1,param2);} ,5000);
mondjunge
  • 1,140
  • 13
  • 24
  • It's not working for me in firefox 33.1.1. I am pretty sure this is an old syntax that was probably supported in all firefoxes including version 3 years ago. – Tomáš Zato - Reinstate Monica May 06 '15 at 09:09
  • This is definitely working in Firefox versions down to version 3 as long as you obey the closure rules – devnull69 May 06 '15 at 09:20
  • @devnull69 Well what is it then? For now, I used the anonymous method solution, but I don't like spamming anonymous methods when it's not necessary. Could be a release-specific bug? – Tomáš Zato - Reinstate Monica May 06 '15 at 09:36
  • Not sure what you are doing, but this code definitely works in all browsers for years now. There must be some other problem with your code. I mean: The code you posted above is surely not working as you expect. For example: What is waitReload, when you pass it? undefined. If you want to pass a function, write it in a variable first. – mondjunge May 06 '15 at 09:43
  • @mondjunge You're wrong about that one. Functions can be passed by their names and they can also be refferenced to as variables. Even `myFunction.prop = true` is perfectly valid and often used to simulate static variables. – Tomáš Zato - Reinstate Monica May 06 '15 at 11:07