Good day.

I am writing a browser game on pure js, the method of drawing the entire game is executed in setInterval (method, 10)

after I added the animation (frame change, let's say), I added it to the same method that is called in setInterval.

As a result, the animation is also displayed with a delay of 10, although, the best option is to set its delay to 60: setInterval (anim, 60).

How to call two methods setInterval, so that the first deals with drawing the entire game with a delay of 10, and the second deals with drawing the animation with a delay of 60?

  • one
    so call two methods. Just don't forget to stop the second one when it becomes unnecessary - Grundy
  • one
    For the first time, change the setInterval to requestAnimationFrame - and the FPS should not be different for drawing the whole scene and animation - you shouldn’t do such crutches, specify the question - ampawd
  • It seems to me that js does not provide for two-threading. It will have to be "manually" paralleled. If the task is so difficult, use Flash - it has more opportunities. - nick_n_a
  • I will answer each in order: setInterval does not need to stop, because It runs the rendering method and the entire logic of the game. If the animation is run in this method, it will be played very quickly. I just need one to draw faster and the other slower. I will not use Flash, because the game was conceived entirely on js, I don’t consider other technologies for it. - Crok

1 answer 1

In general, to draw current changes, the best option is to use the requestAnimationFrame method: https://developer.mozilla.org/ru/docs/DOM/window.requestAnimationFrame

Example of use:

 (function render() { requestAnimationFrame(()=>{ render(); method(); }); })(); 

It will issue 60 method calls per second or less if the computer does not cope with current tasks. In addition, there is no point in calculating intermediate data (animations or game models) with a delay of 10ms or less, as this will create an extra load on the processor.

In addition, the setInterval method never gives an "honest" 10ms or any other time passed to it. At first, all calculations will be performed and only after that the inverse timer is started. Also, if you switch to another tab in Chrome, the delay on the hidden tab is artificially increased to reduce the excess load. So in any case, the game model should receive the current current time, for example, Date.now ();