Munerz
Munerz

Reputation: 1182

Angular 4+ Function reloading each time the component loads

So here is the function

    greenToAmber() {
        let x = 0;
        setInterval(function () {
          x++;
          ..... Rest of code
        }, 500);
      }
    }

I've set this component up using the routes as you would expect, I've tried calling the function in OnInit as well, but every time I go this component then off it and back again the counter will launch a second instance of the counter & then a third ect for each time I leave & come back to the page.

From my understanding I thought ngOnDestroy was meant to prevent this, I'm assuming that I'll need to subscribe and then unsubscribe to the function maybe on destroy?

But I'm relatively new to angular 4 so pretty inexperienced.

Upvotes: 2

Views: 395

Answers (2)

Julien METRAL
Julien METRAL

Reputation: 1974

setInterval is not destroyed on component destroy, you have to save the interval id in your class and use clearInterval javascript native function to clean it on your component destroy hook ngOnDestroy:

import {Component, OnDestroy} from '@angular/core';

@Component({ ... })
export class YourClass implements OnDestroy {

    public intervalId: any; 

    public greenToAmber() {
        let x = 0;
        // registering interval
        this.intervalId = setInterval(function () {
          // ..... Rest of code
        }, 500);
      }
    }

    public ngOnDestroy () {
        if (this.intervalId !== undefined) {
            clearInterval(this.intervalId); // cleaning interval
        }
    }
}

Hopes it helps.

Upvotes: 2

Pruthvi Kumar
Pruthvi Kumar

Reputation: 898

You're setting a demon process with setInterval. The behavior you mention is expected. That is how JavaScript works. Its not Angular specific.

SetInterval always returns a ID which you might want to track in your controller. When you want to destroy it, make sure you do it specifically.

eg:

greenToAmber() {
        let x = 0;
        $scope.myDemon = setInterval(function () {
          x++;
          ..... Rest of code
        }, 500);
      }
    }

//Somewhere else; where you want to destroy the interval/stop the interval:
If($scope.myDemon) {
    clearInterval($scope.myDemon);
}

Upvotes: 0

Related Questions