209

Please tell me how to write javascript below in coffeescript.

setTimeout(function(){
    something(param);
}, 1000);
tomodian
  • 6,043
  • 4
  • 25
  • 29

6 Answers6

214

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
Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
184
setTimeout ( ->
  something param
), 1000

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
Nicholas
  • 2,548
  • 1
  • 17
  • 18
  • Take out the parens, and have a cup of coffee ,~) – Billy Moon Jun 27 '12 at 01:23
  • 4
    Does not compile with the parentheses for me. I had to remove them, start the line with a comma, and it works like a charm. – Jeremy Thille Aug 07 '14 at 13:29
  • With parentheses you can also do this in one line. –  May 13 '15 at 20:47
  • 1
    @JeremyThille note that the space in between `setTimeout` and the opening paren is important. The space there means the parentheses are surrounding the closure as the first parameter to setTimeout; if it was directly after the t then coffescript would expect the parentheses to enclose both parameters. – jankins Sep 02 '15 at 21:12
67
setTimeout -> 
  something param
, 1000
Dirk Smaverson
  • 863
  • 7
  • 8
46

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.

maerics
  • 151,642
  • 46
  • 269
  • 291
12

I find this the best method to do the same,

setTimeout (-> alert "hi"), 1000
Mahesh Kulkarni
  • 307
  • 3
  • 11
3

another option:

setTimeout(
    -> something param
    1000
)
Ron
  • 7,588
  • 11
  • 38
  • 42