having a bit of a headache on trying to work this out. What I want to do is have a custom setTimeout with arguments with out having to create a function to pass it. Let me explain by code:
Want to avoid:
function makeTimeout(serial){
serial.close();
}
setTimeout(makeTimeout(sp.name), 250);
what I want to do is somehow just call a 1 liner by like:
setTimeout(function(arg1){ .... }(argument_value), 250);
Can this be done or can you only pass in a no argument function?
You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg. Yeah!
Bookmark this question. Show activity on this post. This SO answer makes a call to setTimeout with four arguments.
Starting from the (optional) third argument, you can specify an arbitrary number of arguments to the JavaScript setTimeout() method, which are all passed through to the provided timeout callback function. For example: function timeoutFunc(... args){ console.
You can pass it an anonymous function that invokes makeTimeout
with the given arguments:
setTimeout(function () {
makeTimeout(sp.name);
}, 250);
There's also an alternative, using bind
:
setTimeout(makeTimeout.bind(this, sp.name), 250);
This function, however, is an ECMAScript 5th Edition feature, not yet supported in all major browsers. For compatibility, you can include bind
's source, which is available at MDN, allowing you to use it in browsers that don't support it natively.
DEMO.
If you don't want to declare a separate function, you can use an immediately invoked function expression and closure, e.g.
// Parameter to use
var bar = 'bar';
// Function to call
function foo(arg) {
alert(arg);
}
// Go…
setTimeout(
(function(arg1){
return function(){
foo(arg1);
};
}(bar)), 2000);
Alternatively, you can use the function constructor:
setTimeout( Function('foo(bar)'), 2000);
Or you can use a string:
setTimeout('foo(bar)', 1000);
which is essentially the same thing. Now wait for howls of "but that's like using eval, and everyone knows eval is evil and a massive security breach — all your firstborn are doomed!"
But seriously, eval
(and the Function constructor) are inefficient and can lead to lazy programming, so use another option, such as the first above.
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