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)