Kishore L
Kishore L

Reputation: 188

Angular 4 recursive function keeps on executing even when wwe navigate to other component

I am having a recursive function which I am using to draw image in canvas. The component is like:

export class AnimationComponent implements AfterViewInit{

constructor(){

 }


ngAfterViewInit(){
 this.animation();
}
animation(){

  requestAnimationFrame(()=>{
  this.animation()
    });
  }    
}

The animation functions keeps on executing even when I navigate to other component. Is there a way to break the execution of animation() in ngOnDestroy?

Upvotes: 0

Views: 102

Answers (1)

anshuVersatile
anshuVersatile

Reputation: 2068

export class AnimationComponent implements AfterViewInit, ngOnDestroy{
animationFrame:any;
    constructor(){

    }


  ngAfterViewInit(){
     this.animation();
  }
  animation(){

  this.animationFrame = requestAnimationFrame(()=>{
  this.animation()
    });
  }  
  ngOnDestroy(){
    cancelAnimationFrame(animationFrame);
  }

}

Upvotes: 1

Related Questions