Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero.

 if(numberOfFiles === 0) {
            clearInterval(this.repeat);
          }

I conducted a test using console.log and found that even though the if condition evaluates to true, the interval is not cleared. The interval keeps running unless I include a return statement after clearInterval. This issue only arises when multiple files are submitted for execution, causing the currentlyRunning array to contain more than one object. It occurs specifically at the end, when the array becomes empty.

In the code snippet below, you can observe the implementation of checking file status and the logic for clearing the interval:

 export class ...... {
     repeat: any;   
     currentlyRunning = [];

OnInit(){......}

      checkFileStatus() {
        let index = 0;
        this.repeat = setInterval(() => {
          let numberOfFiles = this.currentlyRunning.length;
          if(numberOfFiles === 0) {
            clearInterval(this.repeat);
          }
        let file_id = {
          userFileId: this.currentlyRunning[index].id
        }
          this.auth.verifyProgress(file_id).subscribe((res: any)=>{
                if(res.userFileStatus === "Completed") {
                 ..........
                this.currentlyRunning.splice(index, 1);
                  });
                }
                index  = index + 1;
                  if(index >= numberOfFiles) {
                    index = 0;
                  }
                  if(this.currentlyRunning.length === 0) {
                    clearInterval(this.repeat);
                    return;
                }
             },(err)=>{ 
              index  = index + 1;
                if(index >= numberOfFiles) {
                  index = 0;
                }
                if(this.currentlyRunning.length === 0) {
                  clearInterval(this.repeat);
                  return;
               }
            });
        }, 4000);
        }

        }

Answer №1

It seems that your auth.verifyProgress function is accumulating stack executions and needs to be destroyed once it finishes.

Here is a modified version with an added unsubscribe():


      const listener = this.auth.verifyProgress(file_id).subscribe((res: any)=>{
            if(res.userFileStatus === "Completed") {
             ..........
            this.currentlyRunning.splice(index, 1);
              });
            }
            index  = index + 1;
              if(index >= numberOfFiles) {
                index = 0;
              }
              if(this.currentlyRunning.length === 0) {
                clearInterval(this.repeat);
                return;
            }
           listener.unsubscribe();
         }, (err)=>{ 
          index  = index + 1;
            if(index >= numberOfFiles) {
              index = 0;
            }
            if(this.currentlyRunning.length === 0) {
              clearInterval(this.repeat);
              return;
           }
           listener.unsubscribe();
        });

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

What is the best way to showcase a file edited in Emacs within Atom?

The coding project I'm working on is built with Typescript, but I don't believe that's relevant. I've noticed that Emacs has a unique approach to indentation. According to the documentation, in Text mode and similar major modes, the TAB ...

Display a partial form in Rails using Ajax

There is a form displayed in the image below: Next, I aim to render this partial from an ajax call, specifically from .js.erb. However, I am unsure how to pass an object to f from the partial. Take a look at the image below for reference: Is there a way ...

Show various columns in Select2

I am currently utilizing select2 and I am interested in displaying a multicolumn table as a dropdown. In order to achieve this, the width of the drop-down container should differ (be larger) than the input itself. Is it feasible to accomplish this? Furth ...

How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content using node.js and chai.js: expect(res).to.have.header('Content-Type', 'image/jpeg'); expect ...

Angular Universal: Troubleshooting an Unrendered Route

Struggling for hours to make my site Universal and support Server Side Rendering, I came across the issue where the base route '' is not being rendered by the server. Surprisingly, all other routes are functioning properly when directly called fr ...

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

Guide on how to run functions in Angular 2+ directly from the console?

My application is designed to operate within a chromium browser using chromiumfx. With chromiumfx, you can seamlessly run any JavaScript functions as if you were working in a console environment. Here's a snippet of my code: import { Component } f ...

Ajax request results in a 400 error code

Here is the structure of my Ajax call: function Submit() { var objectData = { email: $("#email").val(), firstName: $("#firstName").val(), lastName: $("#lastName").val(), loginMode: $("#login ...

Unable to reach a variable within the class itself

I'm facing an issue with my MobX store. In my Store class, when I try to access this.user.permits.db, I get an error stating that this.user is undefined. I am confused as to why I can't access the @observable user. src/ui/store/store.js file: ...

I am having trouble with the prime number finder in my JavaScript program. It seems to not work for certain values. What could be

I am in the process of developing a code to identify prime numbers less than n. However, I encountered an issue where the code mistakenly flags 33 and 35 as prime numbers. I am puzzled by this unexpected outcome. Here is the code that I have been working o ...

What is the method for transferring the value of a jQuery variable to a PHP variable without using AJAX?

Here is my JavaScript code: $('#affiliates_name').change(function(){ var id = $('#affiliates_name').val(); }); Below is the corresponding HTML: <select id="affiliates_name" style="display: none;" name="affiliates_name"> < ...

Constantly positioning the text cursor over the Textbox

I am currently in the process of developing a webpage that will feature only one text box for displaying information based on the input data provided. Our strategy involves utilizing either a Barcode Scanner or Magnetic Swipe as well as a Touch Screen Moni ...

Is it possible to verify with Jest that ReactDOM.render has been called if it's enclosed in a conditional statement?

I have a React component that conditionally calls ReactDOM.render when root === true to satisfy flow: import React from 'react' import ReactDOM from 'react-dom' import App from './App' const root = document.getElementById(& ...

Ways to obtain every image placed onto an element

Using the img tag within div.image-block sets a background. Images can be added to .block3 through drag and drop. Is there a way to create a container that includes all elements from .image-block? <style> .image-block { position: relat ...

What is the best way to display HTML file references in TypeScript files using VSCode when working with Angular templates?

Did you know that you have the option to enable specific settings in VSCode in order to view references within the editor? Take a look at the codes below: "typescript.implementationsCodeLens.enabled": true, "javascript.referencesCodeLens.enabled": true I ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...

Utilizing JQuery to alter the text color if validation fails when entering a value

Is there a way to change the text in the input box to red when PHP validation fails using JQuery? I had success with Javascript, but it kept disappearing every time I clicked submit... <form class="link-form" method="post" action=""> <la ...

Error occurred due to changed expression after validation

I am facing an issue in my Angular app while implementing checkboxes with ngModel. When I try to implement it, I encounter the following error message. Can someone please help me resolve this problem? Error core.js:5873 ERROR Error: ExpressionChangedAfter ...

Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when th ...

Error message: npm command not recognized while running commands within an Electron application

While developing an electron app, I utilize shell commands with child_process.exec. One of the commands I use is npm run start, which functions perfectly in a development environment. However, upon building the application for production, all npm commands ...