Santa Cloud
Santa Cloud

Reputation: 617

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

Upvotes: 9

Views: 26875

Answers (3)

Ankit Tiwari
Ankit Tiwari

Reputation: 41

var intervalPromise;
$scope.startTimer = function(fn, delay) {
    intervalPromise = $interval(function() {
        fn();                  
    }, delay);
};

$scope.startTimer(hello, 2000);

hello(){
  console.log("hello");
}

Upvotes: 0

luk-alex
luk-alex

Reputation: 321

You can use setInterval() function

setInterval(()=> { this.myFunc() }, timeIntevalSeconds * 1000);

Upvotes: 21

maxime1992
maxime1992

Reputation: 23803

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.

Upvotes: 8

Related Questions