这是Underscore.js的delay
函数的源代码:
_.delay = function (func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function () { return func.apply(null, args); }, wait);
};
这与setTimeout
有何不同?为什么Underscore.js需要delay
?
这是Underscore.js的delay
函数的源代码:
_.delay = function (func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function () { return func.apply(null, args); }, wait);
};
这与setTimeout
有何不同?为什么Underscore.js需要delay
?
这是一种跨浏览器的方式,可以传递额外的参数,并将它们作为回调函数的参数出现,就像setTimeout()
一样。在IE中无法使用该方法。
它可以使您的代码更加优美...
setTimeout(_.bind(function() { }, null, "arg1"), 1e3);
…对比…
_.delay(function() { }, 1e3, "arg1");
我认为这是Underscore方法中不太有用的一种,具体信息可以在Naomi的回答中找到。
为什么 Underscore.js 有一个延迟函数?
因为愚蠢。这个特定的 underscore.js 方法看起来很愚蠢。
缺点
优点
本节意围意让空白
我只是学习使用JavaScript并编写类似以下代码:
var hello = function() {
console.log("hello");
};
var delay = 1000;
window.setTimeout(hello, delay);
简单吧?Underscore.js有时相当无用。老实说,window.setTimeout
就已经完全够用了。
这里是另一个例子,展示如何将参数传递给函数
var Cat = function(name) {
function meow(message) {
console.log(name, "says meow!", message);
}
this.meow = meow;
};
var duchess = new Cat("Duchess");
window.setTimeout(duchess.meow.bind(duchess, "please feed me!"), 2000);
// 2 seconds later
// => Duchess says meow! please feed me!
如果您无法依赖.bind
,您也可以使用闭包。window.setTimeout(function() {
duchess.meow("please feed me!");
}, 1000);
哇,那真是太难了。我要回去使用underscore、lodash和jquery。这个JavaScript的东西太难了!
_.delay
不足以成为一个(或者说完全不是)值得抽象和额外API记忆的改进。 - Mulanaes·thet·ics
这个库的作者利用自己的业余时间开源、讲解并使用它,把它作为介绍JavaScript的一种方式,也许能够激发某些人对闭包作用域的兴趣,进而增强了这个库的吸引力。
仅就这个函数本身的相关性进行争论就像争论一幅画或其他工艺品的相关性。有些人可能喜欢它,而另外一些人可能不喜欢。
你可以喜欢或不喜欢它。我个人更喜欢那些直接点的库。
_.delay, _.defer, _.throttle, _.after
的流程在我看来读起来比window要更好。
此外,通常我也喜欢写node服务端代码(nodejs)而不必在模式之间切换......试试在node中使用window.timeout
会发生什么。
其实没什么,只是它与defer
、debounce
等主题有关。这意味着您可以使用下划线包装符号:
_(yourfunction).delay(1000);
setTimeout
函数。 - Aadit M Shahdelay
更安全,因为你不能传递字符串参数。但我仍然认为,在正常情况下,没有人会把字符串传递给 setTimeout
。你说,“程序员的手是奇怪的东西,有时候当你不注意时他们会在周围加上引号”,这让它听起来几乎像是个笑话。下次你看到那些手的工作,请告诉他们在玩危险游戏之前应该先咨询一下大脑。另外,在提到 @RobG 之前,你忘记在他名字前加上一个 at 符号了。 - Aadit M Shah
.bind
、.call
或.apply
函数的人来说,它本身就没有什么意义。 - Mulanalert('boo')
,那么我可能会将一个字符串传递给 setTimeout。但是我也可以这样做setTimeout(Function('…'),…)
, 那么不支持字符串有什么好处呢? - RobG