File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments