问题
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