Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created February 26, 2014 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcdnl/9238250 to your computer and use it in GitHub Desktop.
Save amcdnl/9238250 to your computer and use it in GitHub Desktop.

AngularJS Debounce Service

Often I update a value like size that updates quite a bit before it is finalized. If I do a AngularJS $watch on that object my update is firing quite a bit and depending on what you are doing might be a performance concern.

This service allows you to debounce those events so you can effectively throttle. Inspired by Ben Alman's jQuery plugin.

Service > throttle.js

define(['angular', 'app'], function (angular, app) {

  app.factory('debounce', function ($timeout, $q) {
      return function debounce(func, wait, immediate) {
          var timeout;
          var deferred = $q.defer();
          return function () {
              var context = this, args = arguments;
              var later = function () {
                  timeout = null;
                  if (!immediate) {
                      deferred.resolve(func.apply(context, args));
                      deferred = $q.defer();
                  }
              };
              var callNow = immediate && !timeout;
              if (timeout) {
                  $timeout.cancel(timeout);
              }
              timeout = $timeout(later, wait);
              if (callNow) {
                  deferred.resolve(func.apply(context, args));
                  deferred = $q.defer();
              }
              return deferred.promise;
          };
      };
  });
});

Usage

$scope.$watch('card.sizeY', debounce(function () {
  $scope.cardSize = getDim();
}, 500, false), true);

you can also hook .then to the end to use it as a deferred too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment