Angular 6 run a function in every X seconds

Use interval from rxjs

Here’s how:

import { interval, Subscription } from 'rxjs';

subscription: Subscription;

...

//emit value in sequence every 10 second
const source = interval(10000);
const text="Your Text Here";
this.subscription = source.subscribe(val => this.opensnack(text));

...

ngOnDestroy() {
  this.subscription.unsubscribe();
}

Alternatively, you can use setInterval which is available as method on the Window Object. So you don’t need to import anything to use it.

intervalId = setInterval(this.opensnack(text), 10000);

...

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

Here’s a SAMPLE STACKBLITZ for your ref.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)