In my React Native TypeScript app, I have a class called Game with a method named startTimer(). This method is responsible for starting a game loop, which involves calling another method within the Game class called oneLoop() every 500 milliseconds. While oneLoop() is an asynchronous function that typically runs quickly, there is a possibility that it may hang or run slowly on occasion. It's important to note that oneLoop() only updates internal game state information and does not handle animations or graphics.
One possible solution to this is using setInterval:
class Game {
...
async oneLoop(): void {
try {
//lots of async code with await here
} catch (error) {
console.log(error);
}
}
startTimer: void {
this.timer = setInterval(this.oneLoop.bind(this),500);
}
My concern is whether if one instance of oneLoop takes too long to execute, will the timer call the next iteration regardless? Or will everything hang until that particular oneLoop finishes? Is there a more reliable way to repeatedly run an asynchronous function like oneLoop() in TypeScript, possibly without relying on setInterval?
It's worth noting that using a while(true) loop that could potentially hang the rest of the app is not an option. I require an approach that mimics a separate thread, ensuring that the async code runs every 500 milliseconds consistently without disrupting or freezing the rest of the application.