如何通过 Coffeescript 编写带参数的 setTimeout

发布于 2024-11-16 22:02:47 字数 124 浏览 6 评论 0原文

请告诉我如何在coffeescript中编写下面的javascript。

setTimeout(function(){
    something(param);
}, 1000);

Please tell me how to write javascript below in coffeescript.

setTimeout(function(){
    something(param);
}, 1000);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

银河中√捞星星 2024-11-23 22:02:48

我认为回调作为函数的最后一个参数是一个有用的约定。例如,Node.js API 通常就是这种情况。因此,请记住这一点:

delay = (ms, func) -> setTimeout func, ms

delay 1000, -> something param

当然,这会增加您进行的每个 setTimeout 的额外函数调用的开销;但在当今的 JS 解释器中,除非每秒执行数千次,否则性能缺陷微不足道。 (无论如何,你在做什么每秒设置数千个超时?)当然

,更直接的方法是简单地命名你的回调,无论如何这往往会产生更可读的代码(jashkenas 是这个习惯用法的忠实粉丝):

callback = -> something param
setTimeout callback, 1000

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:

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?)

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):

callback = -> something param
setTimeout callback, 1000
自由范儿 2024-11-23 22:02:48
setTimeout ( ->
  something param
), 1000

括号是可选的,但以逗号开头对我来说似乎很混乱。

setTimeout ( ->
  something param
), 1000

The parentheses are optional, but starting the line with a comma seemed messy to me.

冰葑 2024-11-23 22:02:48
setTimeout -> 
  something param
, 1000
setTimeout -> 
  something param
, 1000
青衫儰鉨ミ守葔 2024-11-23 22:02:48

这将产生大致等效的翻译(感谢@Joel Mueller):

setTimeout (-> something param), 1000

请注意,这不是精确的翻译,因为匿名函数返回调用 something(param) 的结果,而不是 undefined,如你的片段。

This will result in a roughly equivalent translation (thanks @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.

可爱暴击 2024-11-23 22:02:48

我发现这是做同样事情的最好方法,

setTimeout (-> alert "hi"), 1000

I find this the best method to do the same,

setTimeout (-> alert "hi"), 1000
埖埖迣鎅 2024-11-23 22:02:48

另一种选择:

setTimeout(
    -> something param
    1000
)

another option:

setTimeout(
    -> something param
    1000
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文