8

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

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Santa Cloud
  • 547
  • 1
  • 10
  • 22
  • 1
    That duplicate would work fine in Angular – bugs May 24 '18 at 08:52
  • @bugs How can I implement this in angular? Can you provide me a concrete example please? PS: should I remove this question as duplicate? – Santa Cloud May 24 '18 at 08:52
  • 3
    Possible duplicate of [Call a javascript function every 5 seconds continuously](https://stackoverflow.com/questions/7188145/call-a-javascript-function-every-5-seconds-continuously) – bugs May 24 '18 at 08:54
  • 1
    You can user timer from Observable to call the service after certain interval. – Niladri May 24 '18 at 08:54
  • 2
    basically `constructor() { setInterval(()=> { this.myFunc() }, 60000); }` – Ivar Reukers May 24 '18 at 08:54
  • 1
    Angular uses Typescript, which is just a superset of javascript. You write plain JS in your angular files and it will work just fine – bugs May 24 '18 at 08:54

3 Answers3

20

You can use setInterval() function

setInterval(()=> { this.myFunc() }, timeIntevalSeconds * 1000);
luk-alex
  • 311
  • 1
  • 9
7
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.

maxime1992
  • 22,502
  • 10
  • 80
  • 121
  • Thanks! I've accepted your answer as the most complete, most of that for your suggestion of doing it inside the service! It works fine! By the way, I fused your answer with @luk-alex one and @Ivaro18 comment above so the (working) result I obtained is: `constructor() { setInterval(()=> { this.myFunc() }, 60000); }` inside my service! Your answer works fine too, but I've prefered to use a more simple code! – Santa Cloud May 24 '18 at 09:09
0

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

$scope.startTimer(hello, 2000);

hello(){
  console.log("hello");
}
Ankit Tiwari
  • 41
  • 2
  • 6