Interesting Approach to Handling the Issue!
Resolution:
To address a similar problem, I devised a solution by incorporating the debounce
function into a service inspired by lodash's implementation. For reference, you can find an example of this implementation in this StackOverflow post (referencing @Pete BD's response).
// Setting up an AngularJS service named debounce
app.factory('debounce', ['$timeout','$q', function($timeout, $q) {
// The actual service is defined as a function that takes in the target function and wait time
return function debounce(func, wait, immediate) {
var timeout;
// Creating a deferred object for resolution when it's time to 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;
};
};
}]);
Once set up, I integrated this service within my controller/directive utilizing $watch
and applied it following your provided code snippet:
$scope.$watch('name', debounce(function(newVal, oldVal) {
if(newVal != oldVal) {
$scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
}
}, 500));
Problem Solved!
Case Background:
Additionally, I experimented with the following approach:
$scope.$watch('name', function(newVal, oldVal) {
debounce(function() {
if(newVal != oldVal) {
$scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
},500)();
});
However, I faced dissatisfaction as the watch was triggered twice within 50ms.