0

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
DatCra
  • 253
  • 4
  • 13
  • Possible duplicate of [Is it possible to send a variable number of arguments to a JavaScript function?](https://stackoverflow.com/questions/1959040/is-it-possible-to-send-a-variable-number-of-arguments-to-a-javascript-function) – Joey Pinto Jan 05 '19 at 00:41

1 Answers1

3

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);
}
Dev Yego
  • 539
  • 2
  • 12