I have a function called "tryMe" and I'm calling it without the parenthesis not precisely this but the idea is like what you would do here:
setTimeout(tryMe,200);
how can I pass parameters that I need?
I am using a jquery plugin that enables me to call a function but I have to call it withou the parenthesis or it executes itself upon loading.
Method 1: Using the new operator: The new operator is used to create an instance of an object which has a constructor function. This constructor function can be used to write our own function and then be invoked by the new operator.
When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.
If I fire up my console and key in the following function (or method, depending where it is used)… Using () after a function means to execute the function and return it's value. Using no () means to fetch the function to be passed along as a callback.
Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.
Never return something on a new line without using parentheses. This is a JavaScript quirk and the result will be undefined. Try to always use parentheses when returning something on multiple lines.
setTimeout(function() { tryMe(parm1, parm2); }, 200);
A more robust offering, to ensure that the values of parm1
, parm2
don't change before the timeout fires (per @lincolnk's comment):
setTimeout(function() {
var p1 = parm1;
var p2 = parm2;
tryMe(p1, p2);
}, 200);
@patrick dw, you're right, has to be evaluated before.
You can wrap tryMe
in a closure.
For example:
var f = function(){tryMe('some parameter');};
setTimeout(f, 200);
Here, we create a function object, f
, which calls tryMe
with the desired parameter(s). Then we pass f
to setTimeout
. When the timeout expires, f
will be called, which will in turn call tryMe
with the desired parameters.
A word of warning if you wish to pass in parameters that may change before the timeout gets called (for example, if you are setting several timeouts in a for
loop): you will want to bind those variables like so:
var f = function(someParamter){return function(){tryMe(someParameter);};};
setTimeout(f(someParameter), 200);
The reason simply doing something like
setTimeout(tryMe('some parameter'), 200); //Does not work.
doesn't work is because you are passing the result of evaluating tryMe
instead of the function object tryMe
itself.
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