title: AngularJS $timeout within a resource factory
body: <p>I currently have an angular application which upon user login calls a service to begin a server call to refresh a count, only allowing for a server side return if the user is authenticated.</p>
  
  <pre><code>resource.approvalsCount = 0;
  var approvalsCountTimer;
  resource.getApprovalsCount = function (username) {
      return resource.query({
          username: username,
          q: 'approvalsCount'
      }).$then(function (response) {
          resource.approvalsCount = response.data.count;
          approvalsCountTimer = $timeout(resource.getApprovalsCount, 3000);
          return resource.approvalsCount;
      });
  };
  </code></pre>
  
  <p>When a user logs out I am attempting to cancel that counter otherwise the server will return a 401 unauthorized error by calling a function based on the resource:</p>
  
  <pre><code>resource.cancelTimers = function () {
      $timeout.cancel(approvalsCountTimer);
  }
  </code></pre>
  
  <p>The issue is that the counter continues to run even after I call the cancel upon the $timeout which returns a 401 from the server.  Console logging out the return the cancel function returns true (cancel has worked).  I have tried several different placements of the begin of the $timeout to no avail, is there a way to ensure that all of the $timeouts are canceled?  I don't understand what I am missing in this configuration.</p>
  
  <p><strong>EDIT</strong></p>
  
  <pre><code>angular.module('resources.approvals.approvals', ['ngResource'])
      .factory('Approvals', ['$timeout', '$resource', function ($timeout, $resource) {
      var resource = $resource('/approvals/:username/:requestID', {}, {
          'update': {
              method: 'PUT'
          }
      });
      resource.approvalsCount = 0;
      var approvalsCountTimer;
      resource.getApprovalsCount = function (username) {
          return resource.query({
              username: username,
              q: 'approvalsCount'
          }).$then(function (response) {
              resource.approvalsCount = response.data.count;
              approvalsCountTimer = $timeout(resource.getApprovalsCount, 3000);
              return resource.approvalsCount;
          });
      };
      resource.cancelTimers = function () {
          $timeout.cancel(approvalsCountTimer);
      };
      return resource;
  }]);
  </code></pre>