我使用此代码安全地使用$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();
这是对的吗?
答案 0 :(得分:1)
这里有一些优化,如果它总是与超时中需要执行的功能相同:
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();
});
修改强>
根据this文章,你需要自己销毁超时:)