I am making a demo in which I am fetching data from the server after regular intervals of time using $interval
Now I need to stop/cancel this.
How I can achieve this? If I need to restart the process, how should I do that?
Secondly, I have one more question: I am fetching data from the server after reqular intervals of time. Is there any need to use $scope.apply
or $scope.watch
?
Here is my plunker:
app.controller('departureContrl',function($scope,test, $interval){
setData();
$interval(setData, 1000*30);
function setData(){
$scope.loading=true;
test.stationDashBoard(function(data){
console.log(data);
$scope.data=data.data;
$scope.loading=false;
//alert(data);
},function(error){
alert('error')
}) ;
}
});
This question is related to
javascript
angularjs
angularjs-scope
When you want to create interval store promise to variable:
var p = $interval(function() { ... },1000);
And when you want to stop / clear the interval simply use:
$interval.cancel(p);
$scope.toggleRightDelayed = function(){
var myInterval = $interval(function(){
$scope.toggleRight();
},1000,1)
.then(function(){
$interval.cancel(myInterval);
});
};
var interval = $interval(function() {
console.log('say hello');
}, 1000);
$interval.cancel(interval);
var promise = $interval(function(){
if($location.path() == '/landing'){
$rootScope.$emit('testData',"test");
$interval.cancel(promise);
}
},2000);
Source: Stackoverflow.com