Angular 6 run a function in every X seconds

user10037542 picture user10037542 · Oct 5, 2018 · Viewed 35.3k times · Source

I have a function called

opensnack(text) { ... };

which is opening an angular material snackbar with the given text input.

What I want to do is to call this function like every 10 seconds.

How should I do this?

Answer

SiddAjmera picture SiddAjmera · Oct 5, 2018

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.