Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function every X seconds

Is there any way to fire a function every X seconds or minutes in Angular 2+?

For example, what if I want to lauch a myService.refreshloginStatus() function from my main app.component every 60 seconds?

I found this question searching on the internet but I have no idea if it could work also for this and how to implement that in Angular...Can someone provide me a concrete usage of this in Angular?

PS: let me know in the comments if in your opinion this question could be a duplicate of the linked one and I have to remove it

like image 428
Santa Cloud Avatar asked Nov 30 '22 08:11

Santa Cloud


2 Answers

You can use setInterval() function

setInterval(()=> { this.myFunc() }, timeIntevalSeconds * 1000);
like image 191
luk-alex Avatar answered Dec 06 '22 12:12

luk-alex


const reloadInterval = 60;

timer(0, reloadInterval).pipe(
  mergeMap(_ => this.myService.myHttpCall())
).subscribe()

That's to answer your question. But honnestly I do not think that's a good idea to do that from a component and you should rather do that directly from your service.

Also, if you're looking for a more advanced answer you can take a look here.

like image 38
maxime1992 Avatar answered Dec 06 '22 11:12

maxime1992