Chris T
Chris T

Reputation: 205

TypeScript: How to make code wait / sleep for few seconds before next step?

I have a function which needs to check a value. If it doesn't exist then it needs to wait and then call itself again. Below is the code. But it doesn't seem to wait for 5 sec but keeps executing without waiting it seems. How do I ix it?

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

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

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

Upvotes: 0

Views: 12973

Answers (1)

Sergio Rinaudo
Sergio Rinaudo

Reputation: 2363

I've edited you example code using vanilla js and async/await, you can implement it in Typescript as well

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 called')

Upvotes: 3

Related Questions