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 );
For example: You can take advantage of the closure scope in Javascript to pass arguments to callback functions. Check this example: What are closures? Closures are functions that refer to independent (free) variables.
When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param (s).
JavaScript Callbacks. ❮ Previous Next ❯. "I will call back later!". A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
A callback can be an anonymous function, which is a function without a name like this: In this example, we pass an anonymous function to the filter () function instead of using a separate function. There are two types of callbacks: synchronous and asynchronous callbacks.
You can call it as follows,
var callBack = function(param1, param2) { ... }
window.setTimeout( function(){callBack('foo','bar');}, 1000 );
The way to pass parameters is after the time parameter as is stated in the documentation of settimeout()
.
var timer = window.setTimeout( func, delay, [ param1, param2, ... ]
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:
window.setTimeout( callBack, 1000, [ "foo", "bar" ] );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With