The underscore library provides a debounce function that prevents multiple calls to a function within a set period of time. Their version makes use of setTimeout.
How could we do this in pure AngularJS code?
Moreover, can we make use of $q style promises to retrieve the return value from the called function after the debounce period?
Here is a working example of such a service: http://plnkr.co/edit/fJwRER?p=preview.
It creates a
$qdeferred object that will be resolved when the debounced function is finally called.Each time the
debouncefunction is called the promise to the next call of the inner function is returned.You get the return value from the debounced function by using the then method on the promise.
If you call
logReturnmultiple times in quick succession you will see thelogReturncall logged over and over but only oneaddMsgcall logged.