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?

Monde
  • 25
  • 5
  • 1
    Duplicate of [How does `Array.prototype.slice.call` work?](/q/7056925/4642212) and [call() & apply() vs bind()?](/q/15455009/4642212); related: [How does the “this” keyword work?](/q/3127429/4642212). Did you read the docs? [`apply`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), [`bind`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), [`call`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`slice`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). – Sebastian Simon Aug 18 '21 at 02: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)`. – Sebastian Simon Aug 18 '21 at 02: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 – Monde Aug 18 '21 at 03:11

0 Answers0