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
1

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Only w/ Object.create(null), it worked. What's the difference between with and without it?
Why Object.create(null) instead of just null?
I just think it's a safer way to avoid Global object pollution, any can do though.
How is null a global?
I didn't say it's a global, I just said it's my safest way to avoid Global object pollution. If you know the issue of working with this and Function#call() and Function#apply()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.