0
  _.delay = function(func, wait) {
    var args = Array.prototype.slice.call(arguments, 2);
   
    setTimeout(function(){
      func.apply(this, args);
    }, wait);
  };

This is the source code for the delay function. I'm new to learning JS and was trying figure out what each line is doing with my limited knowledge.

var args = Array.prototype.slice.call(arguments, 2);

My understanding of the line above is that we're essentially converting the arguments passed to the function into an array and using the call method on the array. Am I right here? If so, what does '2' here do? Does it mean that our array starts with arguments[2] (i.e. [arguments[2], ...]?

 func.apply(this, args);

In addition, what does this line do?

3
  • 1
    Duplicate of How does Array.prototype.slice.call work? and call() & apply() vs bind()?; related: How does the “this” keyword work?. Did you read the docs? apply, bind, call, slice. Commented Aug 18, 2021 at 2:16
  • Probably worth mentioning that the this in the apply is useless and is only a placeholder to pass args as the second argument. The modern equivalent of this function would be _.delay = (func, wait, ...args) => { setTimeout(() => func(...args), wait); }. A slightly more useful version would be to remove { and } (or add return before setTimeout) to make use of the timer ID. But this entire delay function seems superfluous. Just use setTimeout directly; it accepts the same arguments as _.delay (in IE ≥10): setTimeout(func, wait, arg1, arg2). Commented Aug 18, 2021 at 2:32
  • Okay. Thank you for the reply. Yeah, I've read them but I still get a bit of confused when you mix them together but I'll try to figure out Commented Aug 18, 2021 at 3:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.