Skip to content
This repository

feat(debounce): Add initial service factory - NEEDS TESTS and DOCS #419

Closed
wants to merge 1 commit into from

2 participants

Dean Sofer Pete Bacon Darwin
Dean Sofer
Owner

This PR is to remind me to follow up on this.

Pete Bacon Darwin

Here is a more correct demo http://plnkr.co/edit/afX9v0?p=preview

Dean Sofer
Owner

I'm closing this as I don't think it adds anything angular-specific over using something like _.js

Dean Sofer ProLoser closed this May 28, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.

Showing 1 changed file with 48 additions and 0 deletions. Show diff stats Hide diff stats

  1. 48  modules/services/debounce/debounce.js
48  modules/services/debounce/debounce.js
... ...
@@ -0,0 +1,48 @@
  1
+/**
  2
+ * uiDebounce service provides a mechanism for creating a wrapper around a function 
  3
+ * that ensures that the wrapped function is not called more frequently than a
  4
+ * given time interval.
  5
+ *
  6
+ * @param {!Function} func The function to be wrapped (debounced)
  7
+ * @param {number} wait How long between called to func
  8
+ * @param {Boolean} immediate If true then the function is invoked on the first call to the
  9
+ * wrapper function, otherwise the call will not happen until after the wait time has expired
  10
+ * @return {Function} A debounced wrapper around the func function.
  11
+ *
  12
+ * @example
  13
+ * function lookup(id) { ... lookup something ... }
  14
+ * var debounceLookup = debounce(lookup, 2000, false);
  15
+ * $scope.doLookup = function(msg) {
  16
+ *   var promise = debounceLookup(msg);
  17
+ *   console.log('called lookup: ', promise);
  18
+ *   promise.then(function(value) {
  19
+ *     console.log('lookup returned:', value);
  20
+ *   });
  21
+ * };
  22
+ */
  23
+angular.module('ui.services').factory('uiDebounce', function($timeout, $q) {
  24
+  return function(func, wait, immediate) {
  25
+    var timeout;
  26
+    var deferred = $q.defer();
  27
+    return function() {
  28
+      var context = this, args = arguments;
  29
+      var later = function() {
  30
+        timeout = null;
  31
+        if(!immediate) {
  32
+          deferred.resolve(func.apply(context, args));
  33
+          deferred = $q.defer();
  34
+        }
  35
+      };
  36
+      var callNow = immediate && !timeout;
  37
+      if ( timeout ) {
  38
+        $timeout.cancel(timeout);
  39
+      }
  40
+      timeout = $timeout(later, wait);
  41
+      if (callNow) {
  42
+        deferred.resolve(func.apply(context,args));
  43
+        deferred = $q.defer();
  44
+      }
  45
+      return deferred.promise;
  46
+    };
  47
+  };
  48
+});
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.