Angular 6 run a function in every X seconds

烂漫一生 提交于 2020-03-21 11:33:52

问题


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?


回答1:


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.




回答2:


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);
}

setTimeout(opensnack, 10000, "my text"); <-- run every 10 second

You can look at this stackblitz example:



来源:https://stackoverflow.com/questions/52671334/angular-6-run-a-function-in-every-x-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!