Reputation: 373
Invokes func after wait milliseconds. Any additional arguments are provided to func when it is invoked.
I can't think of a good way to pass undefined amount of additional arguments into the callback function. Any suggestion?
function delay(func, wait) {
return setTimeout(func, wait);
}
// func will run after wait millisec delay
// Example
delay(hello, 100);
delay(hello, 100, 'joe', 'mary'); // 'joe' and 'mary' will be passed to hello function
Upvotes: 0
Views: 531
Reputation: 553
Define delay like this
function delay(fn, ms) {
var args = [].slice.call(arguments, 2);
return setTimeout(function() {
func.apply(Object.create(null), args);
}, ms);
}
Or if you are an ES6/7 fan
function delay(fn, ms, ...args) {
return setTimeout(function() {
func.apply(Object.create(null), args);
}, ms);
}
Upvotes: 3