1

I have this simple line of code:

timeout() {
  this.tick();

  if (this._running) {
    this._timeoutId = window.setTimeout(this._boundTimeout, this._gameSpeed);
  }
}

startRunning() {
  this._timeoutId = window.setTimeout(this._boundTimeout, this._gameSpeed);
  this._running = true;
}

I know that in requestAnimationFrame, you just need the callback as the argument like so

this._timeoutId = window.requestAnimationFrame(timeout);

But where do I handle this._gameSpeed for requestAnimationFrame?

[UPDATE]: I manage to run by using requestAnimationFrame(this._boundTimeout), but it ignores the FPS, hence it is almost impossible to catch its movement. In terms of adding this._gameSpeed, how do I handle it to add to the requestAnimationFrame?

ralphcarlo
  • 209
  • 6
  • 22
  • checkout https://stackoverflow.com/questions/19764018/controlling-fps-with-requestanimationframe – thedude Oct 04 '18 at 10:22

1 Answers1

1

You have to calculate delta time yourself and only do things if it's greater than your FPS.

Here is a fiddle with an example https://jsfiddle.net/qnkf7x9g/

And here is the relevant code.

    const FPS = 2; // Frames per second
    const delay = 1000/FPS;
    let previous = 0;
    
    const loop = () => {
     requestAnimationFrame(loop);
    
     const now = Date.now();
    
     if (now - previous < delay) {
           // Do nothing
      return;
     }
    
     previous = now;
    
     // Do something
     console.log("Hello");
    };
    
    
    loop(); // Start the loop
ankr
  • 647
  • 6
  • 15
  • I'm still confused. Is the FPS `const` variable the `this._gameSpeed` or the `delay`? – ralphcarlo Oct 04 '18 at 10:46
  • `delay` would correspond to your `_gameSpeed`. But usually you talk about FPS. – ankr Oct 04 '18 at 11:13
  • I was able to run using `window.requestAnimationFrame(this._boundTimeout)` without `this._gameSpeed`. However, this ignores the fps. In the case of the two functions `timeout()` and `startRunning`, how would you refactor that in such a way that there is a `now`, `previous`, and `delay/this._gameSpeed`? Currently, my `this._gameSpeed` is at `200` by default. – ralphcarlo Oct 04 '18 at 11:22
  • If your `gameSpeed` is 200ms now, you should just set `FPS = 5;` in my example. `1000 / 5 = 200`. – ankr Oct 04 '18 at 12:02
  • You should do the delta time check inside `boundTimeout` -- provided that's what your calling through `requestAnimationFrame`. – ankr Oct 04 '18 at 12:02