在工厂中无法取消$ interval

时间:2014-09-24 20:26:25

标签: javascript angularjs

我使用启动和停止方法编写了一个长轮询工厂。但是,我无法取消计时器。有什么想法吗?

app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) {
    Poller.start(1, $scope.session.user.user_uuid, function(result) {
      User.data.queues.montage_progress = result.field;
      if (result.field == 100) {
        Poller.stop(); //DOES NOT STOP (see below)
      }
    });
  })

这是工厂:

app.factory('Poller', function($http, $q, $interval, $window) {
  var poll = this;
  poll.timer = null;

  poll.checkProgress = function(field, user_uuid) {
    var deferred = $q.defer();
    $http({
      method: 'GET',
      url: '/api/v1/poll/',
      json: true,
      params: {
        field: field,
        user_uuid: user_uuid
      }
    })
      .success(function(data) {
        deferred.resolve(data);
      }).error(function() {
        deferred.reject("Error checking poll");
      });

    return deferred.promise;
  };

  poll.start = function(url, user_uuid, callback) {
    poll.timer = $interval(function() {
      poll.checkProgress(url, user_uuid).then(function(result) {
        console.log(result);

        callback(result);
      }, function(error) {
        alert(error);
      });
    }, 2000);
  };

  poll.stop = function() {
    $interval.cancel(poll.timer);
  };
  return poll;
});

修改     已按照以下建议将$window.clearInterval更改为$interval.cancel(poll.timer);。但仍然无法取消投票......

1 个答案:

答案 0 :(得分:3)

您应该使用$interval cancel 方法,而不是clearInterval

poll.stop = function() {
   $interval.cancel(poll.timer):
};