_.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?
Array.prototype.slice.callwork? and call() & apply() vs bind()?; related: How does the “this” keyword work?. Did you read the docs?apply,bind,call,slice.thisin theapplyis useless and is only a placeholder to passargsas 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 addreturnbeforesetTimeout) to make use of the timer ID. But this entiredelayfunction seems superfluous. Just usesetTimeoutdirectly; it accepts the same arguments as_.delay(in IE ≥10):setTimeout(func, wait, arg1, arg2).