Skip to content

Commit 82343e6

Browse files
author
Bryce Culhane
committed
Merge pull request #1 from coffeescript-cookbook/master
pull origin
2 parents 9d10d31 + e339ea9 commit 82343e6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

chapters/functions/debounce.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
layout: recipe
3+
title: Debounce Functions
4+
chapter: Functions
5+
---
6+
## Problem
7+
8+
You want to execute a function only once, coalescing multiple sequential calls into a single execution at the beginning or end.
9+
10+
## Solution
11+
12+
With a named function:
13+
14+
{% highlight coffeescript %}
15+
debounce: (func, threshold, execAsap) ->
16+
timeout = null
17+
(args...) ->
18+
obj = this
19+
delayed = ->
20+
func.apply(obj, args) unless execAsap
21+
timeout = null
22+
if timeout
23+
clearTimeout(timeout)
24+
else if (execAsap)
25+
func.apply(obj, args)
26+
timeout = setTimeout delayed, threshold || 100
27+
{% endhighlight %}
28+
29+
{% highlight coffeescript %}
30+
mouseMoveHandler: (e) ->
31+
@debounce((e) ->
32+
# Do something here, but only once 300 milliseconds after the mouse cursor stops.
33+
300)
34+
35+
someOtherHandler: (e) ->
36+
@debounce((e) ->
37+
# Do something here, but only once 250 milliseconds after initial execuction.
38+
250, true)
39+
{% endhighlight %}
40+
41+
## Discussion
42+
43+
Learn about [debouncing JavaScript methods](http://unscriptable.com/2009/03/20/debouncing-javascript-methods/) at John Hann's excellent blog article.
44+

0 commit comments

Comments
 (0)