By emles


2018-10-11 14:12:32 8 Comments

I am new to Angular(6). I am using setInterval function in a component. It is working but when I navigate to another route, setInterval continues to execute. Please help me to identify the reason.

//Calling it in ngOnit()
autosavedraftsolution() {
      setInterval(() => {
        console.log(this.draftSolutionForm);
        if (this.solutionTitleValid) {
          this.savedraftsolution();
        }
      }, this.autoSaveInterval);
    }

//savedraftsolution()
  savedraftsolution() {
    console.log("saving..");

    this.connectService.saveDraftSolution({
      Title: this.draftSolutionForm.get('Title').value,
      Product: this.draftSolutionForm.get('Product').value
    } as Draftsolution).subscribe(draftsol => {
      console.log("saved");

    });
  }

It keeps on showing me "saving.." and "saved" message in console.

2 comments

@T. van den Berg 2018-10-11 14:24:00

Dominic is right. You have to clear the interval when the component is destroyed. You can make something like this

ngOnInit(){
    this.saveInterval = setInterval(() => {}, 1000)
}

ngOnDestroy(){
    clearInterval(this.saveInterval)
}

Make sure that your component implements OnInit and OnDestroy.

@Dominic 2018-10-11 14:15:57

You need to call clearInterval to stop it when your component unmounts:

this.intervalId = setInterval(...);

When your component is unmounting:

ngOnDestroy() {
  clearInterval(this.intervalId);
}

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] In Node.js, how do I "include" functions from my other files?

13 Answered Questions

[SOLVED] Pass parameters in setInterval function

3 Answered Questions

[SOLVED] angular http fetching every time i navigate to component using routing

12 Answered Questions

[SOLVED] Execute the setInterval function without delay the first time

2 Answered Questions

Keeping a component alive during routing in Angular 2

1 Answered Questions

[SOLVED] Angular 2 : Directives and providers in @component decorator

  • 2017-03-30 09:55:31
  • Jay
  • 910 View
  • 0 Score
  • 1 Answer
  • Tags:   angular

2 Answered Questions

1 Answered Questions

Angular view is not updated with default Javascript setInterval function

0 Answered Questions

Angular 2 router reuse components

2 Answered Questions

[SOLVED] Angular 2 passing data to another component

  • 2016-03-15 05:23:16
  • Abhijeet Bajracharya
  • 462 View
  • 1 Score
  • 2 Answer
  • Tags:   javascript angular

Sponsored Content