omega
omega

Reputation: 43843

How to run async functions in a loop in typescript?

If I have this

class Foo {
    constructor(obj:number) {
         // run "Run"
         // run "Run" after 1 second after each time it finishes
    }
    private async Run(obj:number):Promise<void> {
         // some code does uses await
    }
}

when the instance is created, I want it to run Run, and when it finishes it waits 1 second and then it runs Run again, in an infinite loop, but using setTimeout. Also the Run doesn't return any value so it can be void.

How can I do this?

Upvotes: 0

Views: 474

Answers (1)

Andrei
Andrei

Reputation: 12036

here is a code with a few helpers allowing you to do that

class Foo {
    constructor(obj:number) {
       this.startRunning();
    }
    private async startRunning():Promise<void> {
         for(let i = 0;; i++) {
            await this.Run(i);
            await this.delay(1000);
         }
    }
    private delay(timeout: number): Promise<void> {
      return new Promise(res => setTimeout(res, timeout));
    }
    private async Run(obj:number):Promise<void> {
         // some code does uses await
    }
    
}

Upvotes: 1

Related Questions