Execute function every 5 seconds based on the current state

I have a method in my component that retrieves data from the back end and checks statuses. Here it is:

 getRecognitionById() {
    this.loaderService.show(null, true);

    this.vendorWebApiService
      .createRecognition(this.executiveChangeId)
      .pipe(take(1))
      .subscribe((res) => {
        this.vendorWebApiService
          .getRecognition(res.taskRequestId, this.executiveChangeId)
          .pipe(take(1))
          .subscribe((recognitionResponse) => {
            if (recognitionResponse.jobStatus === "completed") {
              this.recognitionData = recognitionResponse;
              this.getLatesFeedback();
            }
            if (recognitionResponse.jobStatus === "failed") {
              alert();
            } else {
              
            }
          });
      });
  }

In this section, I am checking status:

 this.vendorWebApiService
      .getRecognition(res.taskRequestId, this.executiveChangeId)
      .pipe(take(1))
      .subscribe((recognitionResponse) => {
        if (recognitionResponse.jobStatus === "completed") {
          this.recognitionData = recognitionResponse;
          this.getLatesFeedback();
        }
        if (recognitionResponse.jobStatus === "failed") {
          alert();
        } else {

        }
      });

The issue arises when the status is anything other than 'completed' or 'failed'. In such cases, I need to rerun this logic every 5 seconds until after 10 attempts, where an alert needs to be shown.

How should I modify my code to achieve this functionality?

Answer №1

Using rxjs for this task is recommended

    import { interval, Subject, Subscription } from 'rxjs';
    refresher$: Observable<number>;
    refreshSub: Subscription;
    jobStatus: string = "init"
    checkCount = 0

    checkTask Status() {
      this.checkCount++
      this.vendorWebApiService
        .getRecognition(res.taskRequestId, this.executiveChangeId)
        .pipe(take(1))
        .subscribe((recognitionResponse) => {
          jobStatus = recognitionResponse.jobStatus
          this.recognitionData = recognitionResponse
          
       });
     }

    fetchRecognitionDetailsById() {
      this.loaderService.show(null, true);

      this.checkStatus()
    }

    this.refresher$ = interval(5000); // every 5 seconds
    this.refreshSub = this.refresher$.subscribe(() => {
      this.checkStatus()
      if (this.jobStatus === 'completed') {
        this.getLatesFeedback();
      }
      if (this.jobStatus === 'failed') {
         alert()
      } else {
         if (this.checkCount == 10) {
            alert()
         }
      }

   });

Answer №2

Here is a way to accomplish this:

  1. Start by setting up a counter variable.

  2. Create an interval using a 5000ms timer and assign it to a variable.

  3. Stop the interval when the task is successful.

  4. If the task fails, restart the interval as long as the counter is less than 10.

let counter = 0;
let interval = setInterval(() => {
  // ajax().next(() => {
  //   clearInterval(interval);
  // }).catch(() => {
  //   if (counter >= 10) {
  //     clearInterval(interval);
  //   } else {
  //     counter++;
  //   }
  // })
}, 5000);
  • Remember to clear the interval in ngOnDestroy to avoid potential crashes in certain situations.

Answer №3

If observables are used, an approach similar to the following could be attempted:

  fetchRecognitionById() {
    //   Display loader service
    const MAX_ATTEMPTS = 10;
    const DELAY_INTERVAL = 5000;
    this.vendorWebApiService
      .createRecognition(this.executiveChangeId)
      .pipe(take(1),
        mergeMap((res) => (
          this.vendorWebApiService
            .getRecognition(res.taskRequestId, this.executiveChangeId)
            .pipe(take(1),
        ))), map((recognitionResponse: any) => {
          if (recognitionResponse.jobStatus === "completed") {
            this.recognitionData = recognitionResponse;
            this.fetchLatestFeedback();
          }
          if (recognitionResponse.jobStatus === "failed") {
            alert();
          } else {
            throw { error: 'failed' };
          }
        }), retryWhen(errors => errors.pipe(
          scan((errorCount, err: any) => {
            if (err.error === 'failed' || errorCount >= MAX_ATTEMPTS) {
              // Implement code for displaying alert after 10 retries
            }
            return errorCount + 1;
          }, 0),
          delay(DELAY_INTERVAL),
        )));
  }

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

Creating a line chart using d3.js with a pair of arrays

This particular question lacks originality in my opinion. You can find a similar query answered at this link: D3.js: draw simple line graph starting from data arrays. Currently, I am working on a similar task using D3.js v5 instead of v4 as discussed in th ...

Utilizing Javascript and CSS for horizontal alignment from left to right

I have a JavaScript function that generates a list of store locations and creates a DIV beneath the map. Currently, the items are displayed top to bottom on the page. However, I would like to change the layout so that the items are shown as 3 in a row fro ...

Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties: albumId: 1 id: 1 thumbnailUrl: "https://via.placeholder.com/150/92c952" title: "accusamus beatae ad facilis cum similique qui sunt" url: "https://via.placeh ...

My website code being stored in cache by Chrome (as well as other browsers)

Issue: I am facing an issue with hosting a widget on my client's website where the widget needs to be different for each page. To display the widget, the client embeds a script tag on their pages. This script is loaded on every page and the content ...

Troubles encountered while fetching URL parameters in Angular 2

Currently in the process of setting up a confirmation email system for my Angular 2 application with a .NET Core 2 backend. The flow goes like this: user registers -> an email is sent to confirm their account -> they click the link -> they should ...

I'm experiencing a flickering issue with my carousel when it reaches over 10,000 pixels during animation. Could this be related to a jQuery problem

After my carousel moves past 10000 pixels, it starts flickering through multiple elements. I'm utilizing jCarousel Lite: Could this be a jQuery-related issue? My initial assumption is that it may be specific to jCarousel Lite, but there doesn't ...

Converting an HTML ul-li structure into a JavaScript object: Steps to save the structure

My HTML structure uses ul and li elements as shown below: <ul class="treeview" id="productTree"> <li class="collapsable lastCollapsable"> <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div> <span ...

AutomatedPostBack wipes out the data stored in my dropdownlist variable

While using javascript and asp.net, I have encountered an issue with the AutoPostBack function clearing a variable called 'callBackReason' that I declared in Javascript from a dropdownlist. Unfortunately, I need to keep this variable in Javascrip ...

Having trouble getting the installed datejs typings to work properly

As I delve into Typescript due to my interest in Angular 2, I have come across the datejs Javascript library. To incorporate it into my Angular 2 project, I went ahead and installed datejs via npm, ensuring that it is correctly listed in my package.json. A ...

Should I implement jquery within angular 2, or opt for the current css/js frameworks available?

Embarking on the development of a website with Angular 2, my deadline is set within a month. I need to select a CSS/JS framework that seamlessly integrates with Angular 2. While using jQuery within Angular 2 is discouraged, I am curious if there are altern ...

What is preventing me from subscribing once more to the same EventEmitter after I have unsubscribed?

I have implemented a subscription in the ngOnInit() method of an Angular2 component and then unsubscribed in ngOnDestroy(). However, after reinitializing the component, I encounter the following error: ObjectUnsubscribedError: object unsubscribed The cod ...

Calculating the total sum of choices within select2

Currently utilizing Select2, a jQuery library, to generate a dropdown list. Trying to determine how to accumulate the values of each option selected by the user. Here's the code sample: <!DOCTYPE html> <html> <head> <m ...

What is the best way to showcase specific information from a JSON file?

My JSON data looks like this : let jsonData = [ { "month" : "01" }, { "folders" : [ { "name" : "test1" }, { "name" : "test2" }, { "name" : "test3" } ] }, { "actions" : [ { "id" : "2" }, { "id" : "4" } ] } ] To con ...

Details regarding the enthusiastic execution of Promise callbacks

Is there a specific specification or implementation detail that dictates how quickly the callbacks of a promise are evaluated? For example, if I have: var promise = new Promise((resolve) => { resolve() }); console.log(promise); // there is no p ...

What could be causing the delay in res.render within Angular Universal?

I have embarked on the journey of building an Angular Universal App, and at this stage, I only have the structure of the site in place. I followed a tutorial meticulously to transform my app for Angular Universal. console.log("got Request " + new Date()); ...

Upon introducing the CSS loader into the webpack configuration, TinyMCE unexpectedly ceases to function

My application development journey began with cloning code from https://github.com/DMPRoadmap/roadmap. This project is based on webpack and npm. To integrate select2, I executed npm install select 2 in the lib/assets directory. I aimed to incorporate a ...

strange complications with importing TypeScript

In my Typescript projects, I frequently use an npm module called common-types (repository: https://github.com/lifegadget/common-types). Recently, I added an enum for managing Firebase projects named FirebaseEvent. Here is how it is defined: export enum Fi ...

Netlify is failing to recognize redirect attempts for a Next.js application

After successfully converting a react site to utilize next.js for improved SEO, the only hiccup I encountered was with rendering index.js. To work around this, I relocated all the code from index to url.com/home and set up a redirect from url.com to url.co ...

The Rails application is loading JavaScript three times

I am encountering an issue with my ajax function where it is being triggered multiple times upon click instead of just once. $(document).on('click', '.newGameItem', function() { console.log('start click event'); var a ...

Vue - the <script setup> element is unable to execute scripts

I have a functional widget from Atlassian that works as expected when used in an HTML file: <html lang="en"> <head> <script data-jsd-embedded data-key=<key> data-base-url=https://jsd-widget.atlassian.com src=https://jsd-w ...