how to write setTimeout with params by Coffeescript

JavascriptSettimeoutCoffeescript

Javascript Problem Overview


Please tell me how to write javascript below in coffeescript.

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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

setTimeout ( ->
  something param
), 1000

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

Solution 3 - Javascript

setTimeout -> 
  something param
, 1000

Solution 4 - Javascript

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.

Solution 5 - Javascript

I find this the best method to do the same,

setTimeout (-> alert "hi"), 1000

Solution 6 - Javascript

another option:

setTimeout(
    -> something param
    1000
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontomodianView Question on Stackoverflow
Solution 1 - JavascriptTrevor BurnhamView Answer on Stackoverflow
Solution 2 - JavascriptNicholasView Answer on Stackoverflow
Solution 3 - JavascriptDirk SmaversonView Answer on Stackoverflow
Solution 4 - JavascriptmaericsView Answer on Stackoverflow
Solution 5 - JavascriptMahesh KulkarniView Answer on Stackoverflow
Solution 6 - JavascriptRonView Answer on Stackoverflow