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.
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;
};
};
});
});
$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.