Skip to content

Instantly share code, notes, and snippets.

@rfunduk
Created March 20, 2014 14:09
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 rfunduk/9664532 to your computer and use it in GitHub Desktop.
Save rfunduk/9664532 to your computer and use it in GitHub Desktop.
# Throttled Input event
#
#= provides throttled:input
#
#= require jquery
#
# Delays firing `input` event until user is done typing.
#
# ### Events
#
# `throttled:input`
#
# * **Synchronicity** Async
# * **Bubbles** Yes
# * **Cancelable** No
# * **Target** Field that is receiving input.
#
# ``` coffeescript
# $('input').on 'throttled:input', ->
# filterResults $(this).val()
# ```
#
setup = ->
keypressed = false
inputed = false
timer = null
delay = 100
schedule = (target) =>
clearTimeout timer if timer
timer = setTimeout =>
timer = null
event = new $.Event 'throttled:input', {target}
$.event.trigger event, null, this, true
return
, delay
return
$(this).on 'keydown.throttledInput', ->
inputed = false unless keypressed
keypressed = true
clearTimeout timer if timer
return
$(this).on 'keyup.throttledInput', (event) ->
keypressed = false
schedule event.target if inputed
inputed = false
return
$(this).on 'input.throttledInput', (event) ->
inputed = true
schedule event.target unless keypressed
return
teardown = ->
$(this).off 'keydown.throttledInput'
$(this).off 'keyup.throttledInput'
$(this).off 'input.throttledInput'
$.event.special['throttled:input'] = {setup, teardown}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment