You want to call a function from within that same function.
You can use the named function identifier to call from inside. Named functions have as advantage that they keep their purpose more explicit, it's better readible and maintainable this way.
ping = ->
console.log "Pinged"
setTimeout ping, 1000
With an unnamed function, using @arguments.callee@ which allows for recursion of anonymous functions. Might also have advantage in memory-intensive application.
delay = 1000
setTimeout((->
console.log "Pinged"
setTimeout arguments.callee, delay
), delay)
You want to detect if a function exists and create it if it does not (such as an ECMAScript 5 function in Internet Explorer 8).
Use the :: sign to access prototype methods and to detect the function, also assign to it if non-existent.
unless Array::filter
Array::filter = (callback) ->
element for element in this when callback element
array = [1..10]
array.filter (x) -> x > 5
# => [6,7,8,9,10]
You want to execute a function only once, coalescing multiple sequential calls into a single execution at the beginning or end.
With a named function
debounce: (func, threshold, execAsap) ->
timeout = null
(args...) ->
obj = this
delayed = ->
func.apply(obj, args) unless execAsap
timeout = null
if timeout
clearTimeout(timeout)
else if (execAsap)
func.apply(obj, args)
timeout = setTimeout delayed, threshold || 100