Skip to content

Instantly share code, notes, and snippets.

@lmartins
Created April 11, 2014 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lmartins/10476300 to your computer and use it in GitHub Desktop.
Save lmartins/10476300 to your computer and use it in GitHub Desktop.
Debounce function execution in CoffeeScript
# Based on:
# http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
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
# USAGE
window.addEventListener 'resize', displayViewPortSize
displayViewPortSize = debounce((e) ->
# do something after window resizing stops
, 250, false)
displayViewPortSize = debounce((e) ->
# do something once and then after every 250ms
, 250, true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment