There are quite a few ways to do this.
Method 1: setTimeout extra parameters
Did you know that you can pass setTimeout extra parameters just like you can do with call?
setTimeout(func, 1000, 1, 2, 3);
However suppose you have an array of arguments instead:
setTimeout(func, 1000, [1, 2, 3]); // This will not work
So you need to do the following instead:
setTimeout(function (args) {
return func.apply(this, args);
}, 1000, [1, 2, 3]);
Unfortunately this won't work in older versions of Internet Explorer. However you could always do this:
function applyAsync(f, ms, args) {
return setTimeout(function () {
return f.apply(this, args);
}, ms);
}
You call it as follows:
applyAsync(func, 1000, [1, 2, 3]);
In my opinion this is the cleanest and the fastest solution. However if you want a cleverer solution then:
Method 2: bindable, callable and appliable
My favourite functions in JavaScript:
var bind = Function.prototype.bind;
var call = Function.prototype.call;
var apply = Function.prototype.apply;
var bindable = bind.bind(bind);
var callable = bindable(call);
var appliable = bindable(apply);
I won't explain how it works in detail but this is what you need to know:
- The
bindable function takes a function f and returns a function equivalent to f.bind; and f.bind is partially applied to any additional parameters.
- The
callable function takes a function f and returns a function equivalent to f.call; and f.call is partially applied to any additional parameters.
- The
appliable function takes a function f and returns a function equivalent to f.apply; and f.apply is partially applied to any additional parameters.
The function you are looking for is appliable:
setTimeout(appliable(func, null, [1, 2, 3]), 1000);
This is as clever and elegant as it gets.