Reputation: 14419
I know how to run a function with an interval using angular however what is the cleanest way to run a function every x seconds but wait until the previous call is completed. Sometimes ajax calls can get stuck and take longer for whatever reason, so I don't want several calls to get clogged up.
Is the best way to just have a boolean flag everytime a call starts and ends and check for that or a more simplified way.
Upvotes: 1
Views: 1983
Reputation: 1553
If ensuring that your method gets called again only after the previous completes its execution is what you want to achieve, you should look at using $timeout
(or setTimeout
) instead of $interval
(or setInterval
).
function runAtAnInterval(){
// Do stuff
// Do stuff
// console.log("do stuff");
$timeout(runAtAnInterval, 1000);
}
runAtAnInterval();
Here's an excellent article explaining how timers work in Javascript.
Upvotes: 0
Reputation: 25352
Try like this
$scope.Timer = null
$scope.start = function() {
$scope.Timer = $interval(function() {
// do whatever you wanna to do
}, 1000);
}
$scope.stop = function() {
if ($scope.Timer) {
$interval.cancel($scope.Timer);
}
}
stop interval before ajax call and after sucess callback start it again
Upvotes: 1