Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling.

ngOnInit() {
    this.liveFunction();
}

liveFunction() {
    var list = [{
        "id": 1,
        "timer": 10000,
        "url": "https://www.sampleurl.com/1"
    },
    {
        "id": 2,
        "timer": 20000,
        "url": "https://www.sampleurl.com/users/1"
    }];
    for (var i = 0, len = list.length; i < len; i += 1) {
        (function (i) {
            setInterval(function () {
                this.invokeAPI(list[i].url)
            }, list[i].timer)
        })(i);
    }
}

invokeAPI (url) {
    //do stuff 
}

Answer №1

To make this function properly, you will need to incorporate async/await functionality. Here's an example of how you can do it:

async ngOnInit() {
    await this.liveFunction();
}

async liveFunction() {
    var requests = [{
        "id": 1,
        "timer": 10000,
        "url": "https://www.sampleurl.com/1"
    },
    {
        "id": 2,
        "timer": 20000,
        "url": "https://www.sampleurl.com/users/1"
    }];
    
    for (var i = 0, len = requests.length; i < len; i += 1) {
        (function (i) {
            setInterval(function () {
                this.invokeAPI(requests[i].url)
            }, requests[i].timer)
        })(i);
    }
}

invokeAPI(url) {
    // Perform API request
}

Answer №2

When using function statements, the scope can be lost as shown below:

    for (var i = 0, len = list.length; i < len; i += 1) {
        (function (i) { // This function has a different scope, missing the "invokeAPI" method
            setInterval(function () { // Another function scope without the needed method
                this.invokeAPI(list[i].url)
            }, list[i].timer)
        })(i);
    }

One way to resolve this issue is by using arrow functions:

      for (var i = 0, len = list.length; i < len; i += 1) {
          ((i: number) => {
            setInterval(() => {
                this.invokeAPI(list[i].url);
            }, list[i].timer)
          })(i);
      }

See a working example here: https://stackblitz.com/edit/angular-hvkkas?file=src/app/app.component.ts

Alternatively, you can store "this" in a variable to access the method from a different scope:

    const _self = this;
    for (var i = 0, len = list.length; i < len; i += 1) {
        (function (i) {
            setInterval(function () {
                _self.invokeAPI(list[i].url)
            }, list[i].timer)
        })(i);
    }

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

The issue encountered is when the data from the Angular form in the login.component.html file fails to be

I am struggling with a basic login form in my Angular project. Whenever I try to submit the form data to login.components.ts, it appears empty. Here is my login.component.html: <mat-spinner *ngIf="isLoading"></mat-spinner> & ...

Troubleshooting: Why is my console.log not working in JavaScript

Recently, I've been diving into the world of JavaScript, but for some reason, I can't seem to make console.log function properly. At the top of my HTML document in the head section, I added jQuery like this: <script type="text/javascript" sr ...

Utilizing React Hooks and Firebase Firestore onSnapshot: A guide to implementing a firestore listener effectively in a React application

SITUATION Picture a scenario where you have a screen with a database listener established within a useEffect hook. The main goal of this listener is to update a counter on your screen based on changes in the database: (Utilizing the useEffect hook without ...

The lack of a defined theme in the makeStyles for @mui/styles sets it apart from @material-ui/core

Struggling to update my material-ui from version 4.11 to version 5 and running into problems with themes. import { createTheme } from '@mui/material/styles'; import { ThemeProvider, StyledEngineProvider, } from '@mui/material/styles&apo ...

Tips for avoiding recursive error function calls in Angular 5

Is there a way to avoid repetitive function calls within a recursive function? Take a look at the following code snippet: loadFinalData(id, color){ this.data = this._test.getUrl(id, "white"); this.dataHover = this._test.getUrl(id, "blue"); } pri ...

Return either the promise or the actual object inside the switchMap function

From the coding tutorial on Angular, my goal is to utilize the hero-details.component for updating and creating hero objects. To achieve this, I added a route without an ID specified. Route { path:'detail/:id', component:HeroDetailCo ...

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

Is it necessary to unsubscribe from an Angular HTTP-Request when using switchMap?

I have a question about managing subscriptions in my Angular application. I'm currently using the combineLatest operator to create an observable from two Angular observables, route.params and route.queryParams. This combined observable is then used as ...

Error: Unable to access property 'fetch' of null (discord.js)

Hey there, I'm running into an issue where it's giving me an error saying that the property 'fetch' doesn't exist. I'm using the Replit database for a balance command in discord.js. You can see the error image here. Here is t ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

A guide on implementing Angular-DataTable within a TypeScript project

Hey everyone, I'm currently working on a TypeScript and Angular application. To create a data table, I decided to use Angular-DataTable. After creating a sample application using it, I added the following code to my Controller: constructor(protecte ...

Importing from source code instead of a file in TypeScript: How to do it

I found this code snippet to help with dynamic component loading: loadComponent(name) { var url = this.configurationService.configuration.api_url+"/generator/dynamic-loading/component/"+name; this.http.get(url, {responseType: 'text'}). ...

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

jQuery: Implementing smooth horizontal scrolling functionality

Here is the code I am working with: // General Function $("li a").click(function() { $("li a").removeClass("active"); $(this).addClass("active"); }); // Horizontal Scroll-to Function $("li a").click(function() { var offset = this.getBounding ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

Having trouble with understanding the usage of "this" in nodejs/js when using it after a callback function within setTimeout

It's quite peculiar. Here is the code snippet that I am having trouble with: var client = { init: function () { this.connect(); return this; }, connect: function () { var clientObj = this; this.socket = ...

Unable to Retrieve Data When Using ASP.NET MVC with Angular

Currently, I am in the process of learning Angular and have managed to grasp the basics needed to get started. In my ASP.NET Core project, I successfully installed Angular without using the default template in Visual Studio 2017 and was able to run the pro ...

Transferring information to a partial view using a jQuery click event

In my Index view, there is a list of links each with an ID. My goal is to have a jQueryUI dialog box open and display the ID when one of these links is clicked. Currently, I am attempting to use a partial view for the content of the dialog box in order to ...