HunterXxX
HunterXxX

Reputation: 33

typescript calling a function every specific time

I am working on a mobile app using ionic and typescript. I want to update the location on the user every 10 min for example

So my idea is to call a function every 10 min like this

function yourFunction(){
  // do whatever you like here
  setTimeout(yourFunction, (1000 * 60) * 10);
  }

  yourFunction();
}

So, is this ok? I mean is this function will execute even if the application is not running? Like for example I am using another, is this function going to execute?

Upvotes: 1

Views: 2828

Answers (3)

Deepak Kamat
Deepak Kamat

Reputation: 1980

This is wrong, as each time yourFunction run it calls itself again, which would result in infinite recursion.

A better way to do this is to use setInterval and outside the function you are calling itself like this

function yourFunction(){
    // Do the stuffs here
}

var theRunner = setInterval( function(){
    yourFunction();
}, (1000 * 60 * 10)); 

Upvotes: 0

Tobias Fuchs
Tobias Fuchs

Reputation: 938

i would prefer to use

setInterval(yourFunction, time_in_ms);

but your solution should work aswell if you do it like this:

function yourFunction() {
   setTimeout(yourFunction, time_in_ms);
} 
yourFunction();

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249556

You can use the setInterval function that does exactly this, and allows you to cancel the interval as well:

function yourFunction() { console.log("Repeading"); }
let id = setInterval(yourFunction, 100)
clearInterval(id); // top stop the repetition

Upvotes: 3

Related Questions