↖️ Show all posts

Debounce functions with coffeescript

#Debounce Functions

You want to execute a function only once, coalescing multiple sequential calls into a single execution at the beginning or end.

Solution example taken from coffeescript cookbook With a named function:

debounce: (func, threshold, execAsap) ->
  timeout = null
  (args...) ->
    obj = this
    delayed = ->
      func.apply(obj, args) unless execAsap
      timeout = null
    if timeout
    else if (execAsap)
      func.apply(obj, args)
    timeout = setTimeout delayed, threshold || 100

so you can use it like this:

mouseMoveHandler: (e) ->
  @debounce((e) ->
    # Do something here, but only once 300 milliseconds after the mouse cursor stops.

someOtherHandler: (e) ->
  @debounce((e) ->
    # Do something here, but only once 250 milliseconds after initial execution.
  250, true)

⬅️ Read previous Read next ➡️