Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End interval when route changes in Angular 2

I start a timer in an Angular 2 component which is inside a router outlet.

setInterval(() => {
    ...
}, 10000);

When I leave the route in which the component is embedded the timer isn't quit. How can I achieve that?

like image 315
daniel Avatar asked Feb 22 '16 18:02

daniel


1 Answers

You could clear the interval from this hook. Mine is controlled from the component/view.

export classTestInterval implements OnInit, OnDestroy{
     public timerInterval:any;
     ngOnInit(){
       // Need interval scope in the component could be from somewhere else, but we need scope to be able to clear it on destruction of component.
       this.timerInterval = setInterval(function(){...},10000);
     }
     ngOnDestroy() {
        // Will clear when component is destroyed e.g. route is navigated away from.
        clearInterval(this.timerInterval);
     }
}
like image 122
inoabrian Avatar answered Sep 21 '22 20:09

inoabrian