How to add a delay in TypeScript code before proceeding to the next step?

I am working on a function that needs to check a value. If the value doesn't exist, it should wait for 5 seconds and then call itself again. The code snippet is provided below, but it seems like it's not waiting for the specified time and keeps executing immediately. How can I fix this issue?

  loadAPI(status: string) {
   .....

          if (this.result === "done") {
            .....
          }
          else
          {
            this.sleep(5000);
            loadAPI(this.status);
          }
    }});
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

Answer №1

I have revised the sample code to use vanilla JavaScript with async/await functionality, you could also implement it in TypeScript.

class App 
{
    async loadAPI(status) {
        console.log(status)
        
        if (false) {
         
        }
        else
        {
            await this.sleep(2000);
            this.loadAPI(status);
        }
    }

    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

(new App).loadAPI('loadAPI function called')

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

Utilizing a single Observable across multiple Pages and Components through a Service

I am attempting to subscribe to the same Observable multiple times, but it is not working as expected. I have a Provider that retrieves the Observable from an AngularFirestore object. Here is my provider: @Injectable() export class MyProvider { private ...

Guide to dynamically loading asset images within an Angular component

I've been attempting to dynamically load images into a carousel on my page, but I'm facing an issue with the code. Here's what I have so far: <div id="carousel" class="carousel slide" data-ride="carousel"> <div class="carouse ...

Nesting two ngFor loops in Angular using the async pipe leads to consistent reloading of data

In my Angular application, I am trying to retrieve a list of parent elements and then for each parent, fetch its corresponding children (1 parent to n children). Parent Child1 Child2 Parent Child1 Parent3 Child1 Child2 Child3 Initially, I succes ...

MockStore has not been configured as a provider

My current challenge involves testing my app.component using Cypress. This component is supposed to fetch data from the ngrx store, and I've made sure to refer to the official documentation for guidance on setting up the test. Here's how the test ...

Utilizing trackingjs as an external library in Ionic2

I have been attempting to incorporate the trackingjs library (https://www.npmjs.com/package/tracking) into my ionic2 project. Following the guidelines in the documentation (https://ionicframework.com/docs/v2/resources/third-party-libs/), I was able to suc ...

Using TypeScript's destructuring feature

Currently delving into the world of TypeScript and I've got a question regarding destructuring. Let's say I have an object that needs to be destructured before using the variables. Here's an example: type bookProps = { books: Book[], ...

What steps should I take to eliminate the npm error from appearing in the protractor's logs whenever a spec fails?

I recently began using Protractor with Jasmine for testing an Ionic2 application. However, I have encountered two major issues that I have been unable to resolve despite extensive research: 1.)Whenever any of my specifications fail during testing, the err ...

`Getting the full URL using a route name in Angular 2 - a step-by-step guide`

Within my Angular 2 (final) project, there is a recurring need to generate full absolute URLs based on route names (such as '/products'). This requirement arises for tasks like providing permalinks to specific pages or opening a page in a new tab ...

How to turn off automatic password suggestions in Chrome and Firefox

Currently, I have integrated a 'change password' feature which includes fields for 'old password', 'new password', and 'retype password'. However, the autocomplete feature is suggesting passwords from other user acco ...

I am attempting to create a multi-line tooltip for the mat-icon without displaying " " in the tooltip

I attempted to create a multiline tooltip using the example below. However, the \n is showing up in the tooltip. I am looking to add a line break like we would with an HTML tooltip. Check out the code here. ...

How to customize the color of md-radio-button in Angular?

I've been trying to customize the color of my radio buttons, but I haven't had much luck. Here are a couple of examples I attempted: Example 1 HTML <md-radio-button class"radio-button"> yes <md-radio-button> CSS //checked .radio- ...

What is the best way to retrieve the file path of a imported Angular module?

I am trying to figure out how to retrieve the path of the BarComponent within the code snippet below. Specifically, I need to obtain '../bar/bar.component'. When dealing with a module loaded from a package such as Component module, I would like t ...

"Encountering an undefined Angular object after making an HTTP request

I've encountered a challenge that seems straightforward to most, but after investing substantial time in it, I've come to the realization that I need some assistance. As part of my project on frontendmentor.io, I'm facing a roadblock with o ...

Transforming a feature into a service rather than a component within the Angular framework

In my Angular2 project, I have implemented a remove function in the component.ts file that removes an item based on its id. I am now wondering how I can pass this function to the service class. Here is the code for the function: removeProduct(id: any,nam ...

Update of input not available

Does anyone know how to effectively transfer data from one page to another programmatically? I'm facing an issue where updating an input field doesn't work unless I manually edit it afterwards. Is there a better way to achieve this? Another prob ...

What is the best way to transfer an object from the view to the controller in AngularJS and ASP.net MVC

How to pass an object with a specific amount of data from the View to the Controller using ASP.net MVC and AngularJS VIEW var Person = {}; Person.IdPerson = 69425; Person.Year = new Date().getFullYear(); $http.post('/API/Update_Person', { para ...

Issue with module not found error while importing TypeScript library

In my TypeScript library, I have created models and API calls for multiple web applications that share the same backend. My goal is to export these models and functions in modules so that consumer apps can import them like this: import { SomeType, SomeFun ...

Encountering issues with dialogues while running Angular 4 NG Build in production mode

I encountered these errors while attempting to run NG Build --Prod (for AoT compilation) ERROR in ng:///C:/Users/DTurcich/DashboardConsole/ASCI.DashboardConsole.Frontend/src/app/add.notification.one.dialog.component.html (7,96): Property 'newAdmin&ap ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...

Acquire the Angular Type<> directly from the component instance in Angular 5

First and foremost, I want to clarify that my requirement is for the Angular Type instance of a component, not just the TypeScript definition. The current scenario is as follows: I am working within a service where I receive an input of the actual instanc ...