0

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?

2
  • 1
    while (true) { await delay(1000); … } Commented Jul 26, 2020 at 20:59
  • 2
    A constructor should not start an asynchronous process. Commented Jul 26, 2020 at 20:59

1 Answer 1

1

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
    }
    
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if i goes past the max int?
uh, it won't. Number.MAX_SAFE_INTEGER is suuuuper long. earth will be destroyed before you wait for that many ticks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.