setInterval never stops


#1

Hello every one, here is my problem I set an interval but it never stops even if I call clearInterval(x) :

:code:
getMatches() {
    let dataToBeSentBack;
    let matchesPromise;
    return new Observable(observer => {
      let interval   = setInterval(() => {
      matchesPromise = this.http.get(this.matchesURL)
              .toPromise()
              .then(response => {observer.next(response.json());})
              .catch(this.handleError);
      }, 3000);
      return (interval) => {
        console.log("inside the return of the observable");
        clearInterval(interval);
      }
    });
  }
ngOnInit(){
    let matchesServiceDisposable = this.matchesService.getMatches().subscribe(
      data => {this.matches = data;},
      err  => this.showError(err)
    );
    setTimeout(() => {
      console.log("called the unsubscribe");
      matchesServiceDisposable.unsubscribe();
    }, 10000);
  }

console output :

matches.js:29 called the unsubscribe
matches.service.js:31 inside the return of the observable

the onNgInit() function is called by the system and this last one subscribe to the observable returned by the service on other terms onNgInit call getMatches() automatically just 1 time.

thanks for your help


#2

yeah because the interval property is not set …

return (interval) => {
    console.log("inside the return of the observable");
    clearInterval(interval);
}

this interval parameter has no value…
remove it as a parameter and it should work.

And another hint… the http-service returns an observable… no need to create an own.


#3

thank you for your answer, the strange thing is that I was doing this from the start I mean return () => {…}
but after I while it was not working I was desperate and I started testing several things around, forgot about this parameter.
probably this worked after all because I restarted the dev server :wink:

regarding the promise returned by http-service I can’t use an internal interval in this one this is why I used ToPromise and returned my proper promise, I’m open to any other suggestions.