I am trying to write a generic debouncer to execute the handling function only once in a particular time period for multiple invocations. I am new to javascript and async programming and therefore am unfamiliar with use of the promise pattern. I tried my hand at it using some help from non-angular code on the web, but I am not able to make it work so that I can get the return value from the invoked function. Can someone please help.
.factory('dnDebounce', ['$timeout', function($timeout) {
return {
debounce: function (scope, func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap) {
func.apply(obj, args);
}
timeout = null;
};
if (timeout) {
$timeout.cancel(timeout);
}
else if (execAsap) {
scope.$apply(func.apply(obj, args));
}
timeout = $timeout(delayed, threshold || 100, true);
return retv;
};
}
};
}])