Skip to content

Instantly share code, notes, and snippets.

@samholst
Forked from lmartins/Debounce.coffee
Created July 27, 2019 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samholst/82df054ec81afd92aa0ae36b663b3bd9 to your computer and use it in GitHub Desktop.
Save samholst/82df054ec81afd92aa0ae36b663b3bd9 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