以javascript或angular清除轮询超时

问题描述 投票:1回答:2
function scan (id) {    
    $http({
            method: "POST",
            url:( "url"),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: $.param({id: id}),
        })
            .then(scanComplete)
            .catch(function(message) {
                throw new Error("XHR Failed ",message);
            });

        function scanComplete(response, status, headers, config) {
            //do something , show errors, popup , call to other functions
        }
  setTimeout(function() {scan())}, 1000);
}

这是我的轮询功能,用于检查数据库中是否有新的通知。

我根本没有清除超时并且不使用$ timeout。这是错误的吗?是因为冻结或CPU开销等问题?

我该如何清除,如何检查我是否真的清除了它

所有功能和ui方面。来自角度服务/工厂没有控制器(除了服务电话)

javascript angularjs polling
2个回答
1
投票

您只需要在scanComplete函数中再次调用

function scanComplete(response, status, headers, config) {
    //do something , show errors, popup , call to other functions
    setTimeout( scan, 1000); //invoke after your ajax is complete
}

这将确保您在任何给定的时间点只发射了一个scan

我根本没有清除超时并且不使用$ timeout。这是错误的吗?是因为冻结或CPU开销等问题?

由于你只是在任何时间点发射一个scan,并且在第一个完成后也是如此,我不知道这将如何产生任何CPU开销。


0
投票

您可以在根控制器中侦听$ destroy事件,并调用清除超时的服务的公共方法:

module.factory("myService", function($scope, $timeout) {
     
  var timer;
     
  function scan (id) {    
    // $http......
    timer = setTimeout(function() {scan())}, 1000);
  }

  function destroyTimer() {
      if (timer) {
          $timeout.cancel(timer);
      }
  }
 
  return {
     destroyTimer: destroyTimer,
     // ...
  }

});

module.controller("RootController", function($scope, $timeout, myService) {
  $scope.$on("$destroy", function() {
      myService.destroyTimer();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.