Angular 6 run a function in every X seconds
Try to use setInterval
setInterval
will allow to run a function regularly with the interval between the runs
https://javascript.info/settimeout-setinterval
Example:
function opensnack(text: string) : void {
console.log(text);
}
setInterval(opensnack, 10000, "my text"); <-- run every 10 second
You can look at this stackblitz example:
You can make use of rxjs
library to run a function every X seconds.
import { interval } from 'rxjs';
import { takeWhile } from 'rxjs/operators';
...
interval(1000)
.pipe(takeWhile(() => !stop))
.subscribe(() => {
// place you code here
});
The above code snippet will execute the subscribed statements every 1 second, until the stop
condition becomes true.
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.