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?
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.