为什么第一次执行延迟不起作用?
另外,在不使用 Array.prototype.slice.call 的情况下,第三个是如何工作的?
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(func(args), wait);
};
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function() { return func.apply(this, args); }, wait);
};
_.delay = function(func, wait) {
return setTimeout.apply(this, arguments);
};
最佳答案
Why does the first implementation of delay not work?
因为setTimeout(<strong>func(args)</strong>, wait);
调用func
。现在。在将调用结果传递给 setTimeout
之前。但这确实需要稍后调用回调函数!
Also how does the 3rd one work without using Array.prototype.slice.call?
因为 apply
也接受 arguments
objects直接,而不仅仅是数组。然而,我想你实际上想知道为什么
_.delay = function(func, wait, ...args) {
return setTimeout(func, wait, ...args); // using rest arguments
};
有效吗?因为那就是 setTimeout
处理多余的参数1 - 它将它们传递给延迟的 func
打电话。
1:在大多数实现中。旧版 IE 没有。
关于javascript - 下划线_.延迟执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092709/