Recursive Problems - Too Much Memory - Angular 9 - Settimeout()

Asked

Viewed 71 times

6

Guys, I’m building an API and I need to make requests every three seconds on the server.

Follows the code:

countAcess() {
    if (this.menuExa && this.appService.requestValid()) {
      this.appService.getCountg()
        .subscribe(
          data => {
            if (data) {
              this.monitor.userc = data;
            }
          });
    }
    clearTimeout(this.setTimeVerific);
    this.setTimeVerific = setTimeout(valida => { this.countAcess(); }, 2500);
  }

My problem is memory, filled 16GB of RAM in about 8/10 hours, will lock any machine. How can I empty this memory or even spend less? I know this because, if I disable the function SetTimeOut(), memory does not inflate consumption

1 answer

7


That one subscribe must have a unsubscribe. This is common practice in other libraries but also in Angular. That is, to invoke the subscribe returns a callback to be able to do unsubscribe, and so at the beginning of this function countAcess it would be good to unsubscribe from the previous one so as not to accumulate new subscriptions and fill memory.

It would be something like that:

countAcess(unsubscribe) {
  if (this.menuExa && this.appService.requestValid()) {
    if (unsubscribe) unsubscribe();
    unsubscribe = this.appService.getCountg()
      .subscribe(
        data => {
          if (data) {
            this.monitor.userc = data;
          }
        });
  }
  clearTimeout(this.setTimeVerific);
  this.setTimeVerific = setTimeout(valida => {
    this.countAcess(unsubscribe);
  }, 2500);
}

The idea is to always have the last accessible unsubscribe to be called before making a new subscribe and thus free memory.

  • 1

    Friend, that’s right! Thank you for asking for an answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.