Very interesting Use Case!
Solution:
I solved a similar issue by implementing the debounce
function in a service taking inspiration from lodash' implementation (also can find an implementation here (@Pete BD's answer).
// Create an AngularJS service called debounce
app.factory('debounce', ['$timeout','$q', function($timeout, $q) {
// The service is actually this function, which we call with the func
// that should be debounced and how long to wait in between calls
return function debounce(func, wait, immediate) {
var timeout;
// Create a deferred object that will be resolved when we need to
// actually call the func
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;
};
};
}]);
Then I included it in my controller/directive containing the $watch
and then doing the magic like so (using your code):
$scope.$watch('name', debounce(function(newVal, oldVal) {
if(newVal != oldVal) {
$scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
}
}, 500));
DONE!
Case history:
I also tried to do like:
$scope.$watch('name', function(newVal, oldVal) {
debounce(function() {
if(newVal != oldVal) {
$scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
},500)();
});
but without satisfaction because the watch was run twice in 50ms.