End interval when route changes in Angular 2

16,287

Solution 1

This should do it:

routerOnActivate() {
  this.timer = setInterval(()=>{
                ...
            }, 10000);
}

routerOnDeactivate() {
  clearInterval(this.timer);
}

Solution 2

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);
     }
}

Solution 3

Maybe for what you want is better OnDeactivate from angular2/router (and maybe also OnActivate depending on your usecase) because you said you want to end the timer when the user leaves the route If I understand it correctly.

export Compnent implements OnInit, OnDeactivate {
    private timer;

    ngOnInit(){
        this.timer = setInterval(_ => {
            // disco
        }, 10000);
    }

    routerOnDeactivate() {
        clearInterval(this.timer);
    }
}
Share:
16,287
daniel
Author by

daniel

Always searching for contracts as a freelancer. My Blog https://zuidinga.de Newest Project: Cloud based FEA/FEM Simulation Moreover i am developing a site for engineers where they can find machine parts from manufacturers: http://www.engineeringonline.de (I am mechanical engineer besides my coding life) I am self employed. I prefer c#/.NET over Java at the moment and static typed languages compared to dynamic scripting languages.

Updated on July 28, 2022

Comments

  • daniel
    daniel almost 2 years

    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?