Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a working example of such a service: <a href="http://plnkr.co/edit/fJwRER?p=preview" rel="noreferrer">http://plnkr.co/edit/fJwRER?p=preview</a>. It creates a <code>$q</code> deferred object that will be resolved when the debounced function is finally called.</p> <p>Each time the <code>debounce</code> function is called the promise to the next call of the inner function is returned.</p> <pre><code>// 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 &amp;&amp; !timeout; if ( timeout ) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { deferred.resolve(func.apply(context,args)); deferred = $q.defer(); } return deferred.promise; }; }; }]); </code></pre> <p>You get the return value from the debounced function by using the then method on the promise.</p> <pre><code>$scope.addMsg = function(msg) { console.log('addMsg called with', msg); return msg; }; $scope.addMsgDebounced = debounce($scope.addMsg, 2000, false); $scope.logReturn = function(msg) { console.log('logReturn called with', msg); var promise = $scope.addMsgDebounced(msg); promise.then(function(msg) { console.log('Promise resolved with', msg); }); }; </code></pre> <p>If you call <code>logReturn</code> multiple times in quick succession you will see the <code>logReturn</code> call logged over and over but only one <code>addMsg</code> call logged.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload