Reputation: 26281
I have an $interval
function that is executed every 1 second.
Basically, the function fetches the user credentials from local storage and checks if the credentials are expired. If they are, then proceeds to refresh the credentials with new ones. If they are not, then it does nothing.
Here is my what my function looks like:
$interval(function () {
var credentials = JSON.parse(storage.fetch('credentials'));
if (credentials && (credentials.expiration <= Date.now()) {
session.refresh(credentials);
}
}, 1000);
The problem here, is that once the credentials expire, the function will try to refresh them. But this task takes more than one second, so the next interval tick will see that the credentials are still expired and try to refresh them again. This will happen for at least 3 seconds.
So, I thought of maybe cancelling the refresh interval when my credentials are being refreshed and then resume it when I'm done:
var refreshing = $interval(function () {
var credentials = JSON.parse(storage.fetch('credentials'));
if (credentials && (credentials.expiration <= Date.now()) {
session.refresh(credentials).then(function () {
// How do I resume the interval function here ??
});
$interval.cancel(refreshing);
}
}, 1000);
But, as you can see in the code above, I have no idea how to resume the function inside the promise callback.
Redefining the function is not an option since I will face the same problem, as I'm having a recursive issue here.
What can it be done to solve this problem?
Also, if this interval approach is not a nice solution, I'm happy to hear tips or best practices!. I'm currently new to AngularJS so I'm still learning how to do things properly.
Upvotes: 0
Views: 58
Reputation: 613
You can not cancel $interval and check if refresh in progess. And you not able to every time create new $interval or $timeout.
var progress = false;
$interval(function () {
if(progress){
return;
}
var credentials = JSON.parse(storage.fetch('credentials'));
if (credentials && (credentials.expiration <= Date.now()) {
progress = true;
session.refresh(credentials).then(function(){
progress = false;
});
}
});
Upvotes: 0
Reputation: 222528
When some degree of control is required over setInterval
/$interval
, the best practice is to replace it with recursive setTimeout
/$timeout
.
function checkCredentials() {
var credentials = JSON.parse(storage.fetch('credentials'));
if (credentials && (credentials.expiration <= Date.now()) {
session.refresh(credentials).then(function () {
return $timeout(checkCredentials, 1000);
});
} else {
$timeout(checkCredentials, 1000);
}
}
checkCredentials();
Upvotes: 1