Observable Interval Subscription

The following example show how to setup a observable interval for 5 seconds. Note that observable interval will call the callback function periodically, in this case 5 seconds each, until it has been unsubscribe(). Since we unsubscribe the observable in the callback function here, it would than be a one time call. It is important to unsubscribe the observable interval once your are done with it, or it will cause memory leakage once your leave the component contains it.

import {Component, OnInit} from '@angular/core';
import {Observable, Subscription} from "rxjs";

@Component({
  selector: 'app-root',
  template: '{{myText}}\n' +
    '<hr>\n' +
    '<button type="button" (click)="resetTimer()">Reset Timer!</button>\n',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  myNumbers: Observable<number>;
  mySubscription: Subscription;
  myText: string;

  ngOnInit(): void {
    this.resetTimer();
  }

  resetTimer(): void {
    if (this.mySubscription !== undefined) {
      this.mySubscription.unsubscribe();
    }
    this.myText = "Loading...";
    this.myNumbers = Observable.interval(5000);
    this.mySubscription = this.myNumbers.subscribe(
      (number: number) => {
        this.dismiss();
      }
    )
  }

  dismiss(): void {
    if (this.mySubscription !== undefined) {
      this.mySubscription.unsubscribe();
    }
    this.myText = "Done!";
  }

}