Stop $timeout when starting new controller

老子叫甜甜 提交于 2019-12-03 05:38:25

问题


I'm polling for my data every 2 seconds to keep them updated on the page. My problem is when I visit another page the timeout stays active. How can i cancel my timeout when I visit an new page?

function IndexCtrl($scope, $timeout, RestData) {
    $scope.rd = {};

    (function getRestDataFromServer() {
        RestData.query(function(data){
            $scope.rd = data;
            $timeout(getRestDataFromServer, 2000);
        });
    })();
}

//EDIT I found a solution, but I'm not sure if it's a good one. When i save my timeout to the $rootScope, I can cancel it in all the other controllers.

function IndexCtrl($scope, $rootScope, $timeout, RestData) {
    $scope.rd = {};

    (function getRestDataFromServer() {
        RestData.query(function(data){
            $scope.rd = data;
            $rootScope.prom = $timeout(getRestDataFromServer, 2000);
        });
    })();
}

function newPageCtrl($scope, $rootScope, $timeout) {
    $timeout.cancel($rootScope.prom); 
}

回答1:


There are couple of Angular events that are being broadcasted when route is being changed. You can listen for them within the IndexCtrl using $scope.$on and act accordingly:

$destroy event

var promise = $timeout(getRestDataFromServer, 2000);
...

$scope.$on('$destroy', function(){
    $timeout.cancel(promise);
});

$locationChangeStart

var promise = $timeout(getRestDataFromServer, 2000);
...

$scope.$on('$locationChangeStart', function(){
    $timeout.cancel(promise);
});

$timeout() returns a promise object. This object can be supplied to $timeout.cancel() function to cancel the timeout.




回答2:


Stewie's answer is perfect. I just wanted to share this simple helper function that I use instead of using $timeout directly, so that I never have to think about this issue again:

function setTimeout(scope, fn, delay) {
    var promise = $timeout(fn, delay);
    var deregister = scope.$on('$destroy', function() {
        $timeout.cancel(promise);
    });
    promise.then(deregister, deregister);
}

I added this function to a service called miscUtils, and I inject that service instead of injecting $timeout. Then, for example, to make an "update" function that runs every 30 seconds until $scope is destroyed:

update();
function update() {
    // do the actual updating here
    miscUtils.setTimeout($scope, update, 30000);
}

Edit for those confused about what's going on with deregister:

This function registers a listener for the $destroy event, but once the timeout has completed it is no longer necessary; there is no longer a timeout to cancel. scope.$on returns a function that, when called, deregisters that listener. So, promise.then(deregister) cleans up that no-longer-needed listener as soon as the timeout completes.



来源:https://stackoverflow.com/questions/17131807/stop-timeout-when-starting-new-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!