Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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