I'm struggling with an $interval
function that runs every second.
The function retrieves user credentials from local storage and checks if they have expired. If they have, it refreshes them with new ones. Otherwise, it does nothing.
This is 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 issue I'm facing is that when the credentials expire, the function tries to refresh them. However, this process takes longer than a second, so during the next interval, it detects that the credentials are still expired and attempts to refresh them again. This cycle repeats for at least 3 seconds.
I had the idea of pausing the refresh interval while the credentials are being refreshed and then resuming it once the task is complete:
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);
Unfortunately, I'm uncertain how to resume the function inside the promise callback in the code above.
Recreating the function is not viable as it would create a recursive problem.
If anyone has suggestions on how to approach this issue or better practices in AngularJS development, please feel free to share! I am relatively new to AngularJS and eager to learn proper techniques.