Home > Software engineering >  repeat task as long as component is shown
repeat task as long as component is shown

Time:06-26

I would like to repeat a task regularly. My first attempt was such a setInterval construction in the constructor. The problem is that the execution does not stop when I hide the component and when I show it it even executes 2x. So what is the right way to execute a task WHILE a component is shown (and stop if component ist not shown anymore)?

   // in constructor of component
          setInterval(() => {
    // do something
         
          }, intervall * 1000);

CodePudding user response:

subscription : Subscription ;
ngOnInit()
{
   const observbles = new Observable(sub => {
    //do something.
   this.subscription = observbles.subscribe(x => ....);
});
}

ngOnDestroy()
{
  this.subscription.unsubscribe();
}

NOTE : Do your actions in ngOnInit() and to end it implement it 
 in ngOnDestroy()

It will repeat the task until your are in that component and destroy it when you leave that component I have displayed a demo of observable

CodePudding user response:

Use a timer, you can then subscribe and unsubscribe in the ngOnInit and the ngOnDestroy.

export class MyComponent implements OnInit, OnDestroy {
  interval = 5;
  timerSub!: Subscription;
  
  ngOnInit() {
    this.timerSub = timer(0, this.interval * 1000).subscribe();
  }

  ngOnDestroy() {
    this.timerSub.unsubscribe();
  }
}

CodePudding user response:

Based on Vegas answer (thanks again!) I solved it this way:

  myIntervall = null;
  ngOnInit() {
    this.myIntervall = setInterval(() => {
      console.log(
        'I am called every two seconds as long as this component is shown'
      );
    }, 2 * 1000);
  }

  ngOnDestroy() {
    clearInterval(this.myIntervall);
  }
  • Related