This question already has an answer here:
I'm stumped on how to correctly pass parameters to a callback function without immediately calling that function.
For example, this will work as expected:
var callBack = function() { ... }
window.setTimeout( callBack, 1000 );
But this will accidentally call callBack
:
var callBack = function(param1, param2) { ... }
window.setTimeout( callBack('foo','bar'), 1000 );
You can call it as follows,
The way to pass parameters is after the time parameter as is stated in the documentation of
settimeout()
.The first argument is the actual callback, the second is the time in miliseconds and the last (optional) argument is an array of parameters to pass to the callback.
So, for your example it would be something like:
The title of your question is slightly misleading as the method used to pass parameters to a callback function differs in the implementation of the code that is using it. As you might imagine, the actual function object and it's parameters don't necessarily need to be passed together as the functions execution is deferred to a later time; Only then do the parameters need to come in contact with the callback.
For a more generic explanation of how to pass arguments to a callback object you can take a look at this post: JavaScript: Passing parameters to a callback function.