source

AngularJS $interval 함수는 루트 변경 후에도 계속됩니다.

bestscript 2023. 2. 22. 22:30

AngularJS $interval 함수는 루트 변경 후에도 계속됩니다.

setInterval을 기반으로 하는 컨트롤러 내부에 함수가 있습니다.처음 전화를 걸었을 때는 정상적으로 동작했지만, 루트가 변경되어도 계속 되는 것을 알 수 있었습니다.그 후 스코프의 변경을 자동으로 추적하는 네이티브 $interval 서비스를 사용해 보았습니다.다만, 아직 문제가 발생.이제 두 가지 질문이 있습니다.첫 번째는 사용자가 경로를 이탈하면 정지되는 특정 컨트롤러 내에서 반복 기능을 사용하려면 어떻게 해야 합니까?또, 스코프를 변경했는데 스코프 기능이 계속 되는 이유는 무엇입니까?

업데이트 - 코드는 다음과 같습니다.

$scope.refreshScore() {
        ....
      }
$scope.refreshMe = function(){
  $interval($scope.refreshScore, 10000);
}

스코프 파괴 이벤트에서 취소해 볼 수도 있습니다.

$scope.refreshScore() {
   ....
}
var intervalPromise;
$scope.refreshMe = function(){
    intervalPromise = $interval($scope.refreshScore, 10000);
}
$scope.$on('$destroy',function(){
    if(intervalPromise)
        $interval.cancel(promiseFromInterval);   
});

$interval특히 비동기 조작의 경우에는 최적의 솔루션이 아닐 수 있습니다.반드시 x ms마다 발생시키고 싶은 타이밍에 맞춰 작업을 수행해야 하는 경우 다음과 같은 방법을 사용합니다.

var refreshingPromise; 
var isRefreshing = false;
$scope.startRefreshing = function(){
   if(isRefreshing) return;
   isRefreshing = true;
   (function refreshEvery(){
         //Do refresh
         //If async in then in callback do...
         refreshingPromise = $timeout(refreshEvery,10000)
    }());
} 

그럼 위와 같이 하세요.

갱신을 취소하는 데 문제가 있는 경우 루트 변경 이벤트 등의 서브스크라이브를 시도할 수 있습니다.그리고 거기서 하는 거.

이것을 시험해 보세요.

    $scope.refreshScore = function() {
       // your logic here
    }
    var promise = $interval($scope.refreshScore, 10000);
    $scope.$on('$destroy',function(){
        if(promise)
            $interval.cancel(promise);   
    });

경로를 변경하면 간격이 파괴됩니다.

간단한 솔루션 하나로$location.$$path인터벌과 관련된 이벤트를 기동하기 전에,

경로가 UI와 상관되지 않으면 실행하지 않고 취소하십시오.

언급URL : https://stackoverflow.com/questions/21568494/angularjs-interval-function-continues-after-route-change