Best approach to game loop timer in typescript with no animation

87 views Asked by At

Suppose I have a react native typescript app, and I have a class Game that has a method startTimer(). When startTimer is called, it need to start running a game loop, which means it needs to call the Game method oneLoop() every (say) 500 milliseconds. But oneLoop is an async function, most of the time it runs quickly but it is possible that one instance could run slowly or hang. Also note that oneLoop() just updates some internal game state information. It does not draw any animations or screen objects so I am not worried about choppy animations or graphics.

One approach is to use 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);
    }

I believe that is one invocation of oneLoop takes too long, the timer will call the next one anyway. Or does everything just hang until that oneLoop finishes? Is there a better way to reliably run an async function like oneLoop() repeatedly in typescript, possibly using something other than setInterval?

Note that I cannot use a while(true) loop that hangs the rest of the code. The approach I need is something that acts like a thread that reliably runs async code every 500 milliseconds without disturbing or hanging the rest of the app.

1

There are 1 answers

0
Dimava On

You may do

async doLoops() {
  while(this.keepLooping) { // if it's async `while(true)` is fine
    await new Promise(r => setTimeout(r, 500)) // 500ms between end and next start
    await this.oneLoop().catch(/* ignore errors */)  
  }
}

Then you'll have 500ms between loops (>500ms between call on average tho, need fix?)