Try this piece of code (untested):
var timeoutPromise = null;
$scope.printDistance = function printDistance() {
if (isPositionAvailable($scope.gps_position.Latitude)) {
//Print Distance between 2 points
timeoutPromise = null;
} else {
console.log("### No position to calculate Distance...")
timeoutPromise = $timeout(function() {
$scope.printDistance();
}, 1000);
}
}
$scope.$on('$destroy', function() {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
});
First of all, prefer using $timeout
instead of setTimeout
. $timeout
also calls $apply()
(digest and re-render). setTimeout
does not so you have to call it yourself (you don't seem to call it, though).
The actual solution is to listen to the $destroy
even which is fired when you navigate back to Home. At that point you stop the async task.