Javascript 如何通过 Coffeescript 用参数编写 setTimeout
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6459630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to write setTimeout with params by Coffeescript
提问by tomodian
Please tell me how to write javascript below in coffeescript.
请告诉我如何在coffeescript中编写下面的javascript。
setTimeout(function(){
something(param);
}, 1000);
回答by Trevor Burnham
I think it's a useful convention for callbacks to come as the last argument to a function. This is usually the case with the Node.js API, for instance. So with that in mind:
我认为将回调作为函数的最后一个参数是一个有用的约定。例如,Node.js API 通常就是这种情况。所以考虑到这一点:
delay = (ms, func) -> setTimeout func, ms
delay 1000, -> something param
Granted, this adds the overhead of an extra function call to every setTimeout
you make; but in today's JS interpreters, the performance drawback is insignificant unless you're doing it thousands of times per second. (And what are you doing setting thousands of timeouts per second, anyway?)
当然,这会为setTimeout
您所做的每一次调用增加额外函数调用的开销;但是在今天的 JS 解释器中,除非你每秒执行数千次,否则性能缺陷是微不足道的。(无论如何,你在做什么设置每秒数千次超时?)
Of course, a more straightforward approach is to simply name your callback, which tends to produce more readable code anyway (jashkenas is a big fan of this idiom):
当然,更直接的方法是简单地命名您的回调,无论如何它往往会产生更具可读性的代码(jashkenas 是这个习语的忠实粉丝):
callback = -> something param
setTimeout callback, 1000
回答by Nicholas
setTimeout ( ->
something param
), 1000
The parentheses are optional, but starting the line with a comma seemed messy to me.
括号是可选的,但以逗号开头的行对我来说似乎很混乱。
回答by Dirk Smaverson
setTimeout ->
something param
, 1000
回答by maerics
This will result in a roughly equivalent translation (thanks @Joel Mueller):
这将导致大致等效的翻译(感谢@Joel Mueller):
setTimeout (-> something param), 1000
Note that this isn't an exact translation because the anonymous function returns the result of calling something(param)
instead of undefined, as in your snippet.
请注意,这不是一个精确的翻译,因为匿名函数返回调用的结果something(param)
而不是 undefined,如您的代码段中所示。
回答by Mahesh Kulkarni
I find this the best method to do the same,
我发现这是做同样事情的最佳方法,
setTimeout (-> alert "hi"), 1000
回答by Ron
another option:
另外一个选项:
setTimeout(
-> something param
1000
)