0

When developing an app with a timer in Stackblitz, the interval is not cleared between runs. As in, in the Stackblitz project settings, I specified to reload on saves. But when the app reloads, the old intervals are all still active.

In the ngOnInit method I set a timer on an interval with the code: window.setInterval(this.tick, 1000); And in the function tick() I added logging to see what was going on by adding console.log('log information 1'); statements. Then I change the content of my tick() function to console.log('log information 2'); And afterwards I can see both 'Log information 1' and 'Log information 2' messages appear in my console every second.

I tried keeping track of the intervals by adding a timer variable like: this.appTimer = window.setInterval(this.tick, 1000); and then clearing the old timer before creating a new one by window.clearInterval(this.appTimer); Before doing anything else on a new run. But ofcourse because it is a new run, the variable appTimer is still empty.

Is there a way to just clear all active intervals when reloading Stackblitz? Refreshing the browser does the trick, but that starts and stops the dev server which seems like overkill.

SvG
  • 39
  • 6

1 Answers1

0

Try using an observable interval instead, and use a destroyable observable with takeUntil().

import {interval} from 'rxjs';

@Component({...})
export class ExampleComponent implements OnInit, OnDestroy {
   private destroyed = new Subject();
   ngOnDestroy() { this.destroyed.next(); }
   ngOnInit() {
      interval(1000).pipe(
         takeUntil(this.destroyed)
      ).subscribe(v => console.log(v));
   }
}
Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • I didn't even think to use ngOnDestroy or rxjs functions. Using suscribe and unsuscribe is definately a neater way of working I am going to use in the future. Unfortunately this does not solve my problem. When Stackblitz updates, it doesn't go through the usual events, like the ondestroy method. Which means that the interval still does not get cleared. – SvG Sep 17 '19 at 19:43