Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions chapters/functions/debounce.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
layout: recipe
title: Debounce Functions
chapter: Functions
---
## Problem

You want to execute a function only once, coalescing multiple sequential calls into a single execution at the beginning or end.

## Solution

With a named function:

{% highlight coffeescript %}
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
{% endhighlight %}

{% highlight coffeescript %}
mouseMoveHandler: (e) ->
@debounce((e) ->
# Do something here, but only once 300 milliseconds after the mouse cursor stops.
300)

someOtherHandler: (e) ->
@debounce((e) ->
# Do something here, but only once 250 milliseconds after initial execuction.
250, true)
{% endhighlight %}

## Discussion

Learn about [debouncing JavaScript methods](http://unscriptable.com/2009/03/20/debouncing-javascript-methods/) at John Hann's excellent blog article.