Safe and correct way to reload data on angularjs ($timeout)

為{幸葍}努か 提交于 2019-12-13 07:13:11

问题


I use this code to safe work with $timeout :

        $scope.intervalFunction = function () {
            setTimeout(function () {
                //DO
                console.log('refresh');
                if ($scope.currentNode) {
                    $scope.intervalFunction();
                }
            }, 5000)
        };

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

        $scope.intervalFunction();

it is correct?


回答1:


There are a few optimizations here, if it is always the same function that needs to be executed in the timeout:

var refreshTimeout;

$scope.intervalFunction = function () {
    // Assign to refreshTimeout, so it can be cancelled on the destroy of the scope
    refreshTimeout = $timeout(function() {
        console.log('refresh');
        if ($scope.currentNode) {
            $scope.intervalFunction();
        }
    }, 5000)
};

$scope.intervalFunction();

// Only one timeout to destroy
// Though I don't think this is even necessary, because probably
// the timeout gets cancelled anyway on the destruction of the scope
$scope.$on('$destroy', function () {
    if (refreshTimeout)        
        refreshTimeout.cancel();
});

EDIT

According to this article, you do need to destroy the timeout yourself :)



来源:https://stackoverflow.com/questions/30799521/safe-and-correct-way-to-reload-data-on-angularjs-timeout

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