From 88ebc13bd4a20152fdbcbb36b7bc778d03b3e14d Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Tue, 4 Sep 2012 08:51:46 -0400 Subject: [PATCH] Debounce. --- chapters/functions/debounce.md | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 chapters/functions/debounce.md diff --git a/chapters/functions/debounce.md b/chapters/functions/debounce.md new file mode 100644 index 0000000..2a3b714 --- /dev/null +++ b/chapters/functions/debounce.md @@ -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. +