Pausing and then resuming an interval function within the same function

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.

Answer №1

To maintain a certain level of control over the timing of code execution, experts suggest using recursive setTimeout/$timeout instead of relying on setInterval/$interval.

function verifyAccess() {
   var accessData = JSON.parse(storage.fetch('access'));
   if (accessData && (accessData.expiration <= Date.now()) {
        session.update(accessData).then(function () {
           return $timeout(verifyAccess, 1000);
        });
   } else {
        $timeout(verifyAccess, 1000);
   }
}
verifyAccess();

Answer №2

It is not possible to cancel the $interval and verify if a refresh is currently in progress. Additionally, it's not feasible to create a new $interval or $timeout every time.

var refreshing = false;

$interval(function () {
    if(refreshing){
       return;
    }  

    var storedCredentials = JSON.parse(storage.fetch('credentials'));
    if (storedCredentials && (storedCredentials.expiration <= Date.now()) {
        refreshing = true; 
        session.refresh(storedCredentials).then(function(){
             refreshing = false;
        });
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Seeking a proficient Cloud Code specialist skilled in JavaScript, focused on managing installations and channels

My experience with Javascript is limited, but as I work on my application, I realize the necessity of incorporating it into Cloud Code. I have a Parse class called Groups where I store group data including Name, Description, Users, and Requests. Name, Des ...

Tips for showing data from an hour ago in Angular

Here is the code snippet provided: data = [ { 'name' : 'sample' 'date' : '2020-02-18 13:50:01' }, { 'name' : 'sample' 'date' : '2020-02- ...

Having trouble with closing modal pop-up window after submitting the form

angular.module("simpleModalPop").controller("applicationListCtrl", [ "$scope", "masterService", "$rootScope", "Notification", "applicationService", "Constant", "$filter", "$state","$uibModal", function($scope, masterService, $rootScope, Notification, a ...

Having trouble loading services within my Angular controller

After developing my Angular application, I added some basic code to my controller which is displayed below. Now, I am attempting to include two services that I created in my services.js file. This file is being loaded in my index.html and required within m ...

Creating an event listener with a dynamic name

I'm in the process of developing a customizable button bar where I need to attach onclick event listeners to each button dynamically. The functions to be assigned should have names provided by the button's data-function attribute. … <div cl ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

Error: An unexpected identifier was encountered while executing my function

I've been trying to implement a function that I found online, but when I try to run it in the terminal, I keep getting this error: /home/simone/gekko/strategies/high.js:10 sma: function(name, price, points) ^^^ SyntaxError: Unexpected identifier I ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

Launching a pre-built React application

I'm facing an issue while attempting to run a pre-existing React App on my Mac locally. I have all the source files and node.js installed on my machine. Upon running npm install, I encountered a massive list of deprecations and npm ERRors that surpas ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

What steps do I need to take to retrieve data in a JSON array based on its

Hello, I could really use your assistance with a problem I'm having. Here is the scenario: I have a JSON array that looks like this: "category" : [ { id: 1, product: [{id : product_1, type : ball}] }, { id : 2, product :[{id : prod ...

What is the best way to include a character in a string if there are no instances of the same character already present?

Looking for help with a function that can determine if a string contains a period and add one if it doesn't. So far, I'm struggling to make it either continuously add periods or not add any at all. function checkPeriod() { if (inputString.indexO ...

Using JavaScript to alter CSS styles with dashes

Currently, I'm delving into the world of manipulating CSS using JavaScript: img.style.borderRadius = "100%"; img.style.border = "9px solid #ffffff"; img.style.boxShadow = "0 0 5px #00000070"; img.style.margin = "20px"; I'm wondering how to chan ...

Change the appearance of text with a button click using JavaScript

Currently mastering JavaScript but encountering an issue. How do I change the text to underline when clicking on "Click Me"? <p id="demo" style=" text-decoration:none; ">Hello JavaScript!</p> <button type="button" onclick="document.getE ...

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of prom ...

Retrieving Records within a Specific Date Range for Check-ins and Check-outs

Our team is currently working on developing booking software that requires handling different room pricing based on specific dates. Each room has distinct pricing for weekdays and weekends. ROOM 1 Pricing 1: September 1st - November 3rd, Weekday: $100, W ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

Issue with referencing Asmx web service

I am struggling to properly reference my web service method with JavaScript on my client page. I keep receiving an error message that says "CalendarHandler is not defined". <%@ WebService Language="C#" CodeBehind="~/App_Code/CalendarHandler.cs" Class ...