简体   繁体   中英

Cancelling interval based on a promise result in Angular

I have this business logic where I want to check some data from a service every 1 second, and if that data returns some property to be true, I want to cancel the interval. For example:

  someFn() {
    this.interval = setInterval(this.getData, 1000, param1, param2);
  }

  private async getData(param1: string, param2: string) {
    const data = await this.service.getSomeData(param1);
    if (data && receipt.success) {
      console.log('SUCCESS!');
      console.log('Clearing interval', this.interval);
      clearInterval(this.interval);
    }
  }

However, the interval doesn't stop executing, even though I'm entering the if block and SUCCESS is printed out. The interval seems to be undefined. I'm guessing this is because of some promise magic but I can't quite grasp why. Any help is appreciated.

Edit: The button calling someFn is this.

<button class="btn btn-primary" (click)="myService.someFn()">Do Logic</button>

Edit2: If I console.log(this.interval) inside the someFn function right below where I set it, it logs an id. But inside the getData, this.interval is undefined.

I've figured it out. Instead of passing a reference to the setInterval, I'm executing the function inside the callback. So:

 someFn() {
    this.interval = setInterval(this.getData, 1000, param1, param2);
  }

becomes

 someFn() {
    this.interval = setInterval(() => this.getData(param1, param2), 1000);
  }

and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM