Skip to content

Instantly share code, notes, and snippets.

@patrickfox
Last active August 29, 2015 14:23
Show Gist options
  • Save patrickfox/dc0351a2c2a28a3b153a to your computer and use it in GitHub Desktop.
Save patrickfox/dc0351a2c2a28a3b153a to your computer and use it in GitHub Desktop.
Throttlr - Keep your resize and scroll events in check, yo

##Throttlr Throttle your window events

Throttlr =
	dom_event: null
	timeout: null
	pubsub_event: null
	publish_event: ->
		#specify your own publish method here, or use PubShlub - https://gist.github.com/patrickfox/c9d29ab6f319364dfe3f
		$.publish @pubsub_event
	on_event: ->
		self_timeout = @timeout
		_self = @
		self_publish_event = ->
			_self.publish_event()
		window.clearTimeout self_timeout
		self_timeout = window.setTimeout self_publish_event, @timeout
	init: (dom_event, pubsub_event, timeout) ->
		@dom_event = dom_event
		@pubsub_event = pubsub_event
		@timeout = timeout
		_self = @
		$(window).on @dom_event, $.proxy(@on_event, _self)
	create: (dom_event, publish_event, timeout) ->
		instance = Object.create(Throttlr)
		return instance.init(dom_event, publish_event, timeout)

###Params dom_event - the DOM event to be throttled, e.g. resize, scroll

pubsub_event - the custom pubsub event to be triggered/published

timeout - the minimum interval duration for emitting the specified event

###Usage: Throttle window resize events: Throttlr.create(dom_event, pubsub_event, timeout) window_resize = Throttlr.create('resize', custom_resize_event, 100)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment