How to control framerate / lower cpu usage

Upload your latest creations here, and download the latest creations here! This is where the creative tool shop resides.
Post Reply
Dr. Madskull
Posts: 20
Joined: Tue Jun 04, 2019 11:35 am

How to control framerate / lower cpu usage

Post by Dr. Madskull » Wed Jul 10, 2019 9:28 am

Hi, this is a code example of how to control (lower) the framerate. Main reason would be to lower the cpu usage, but I guess there are any number of uses.

Here is the magic part of the code, checking if enough time has passed:

Code: Select all

  
var fpsInterval = 1000 / 5; // Giving 5 fps.
var Now, ElapsedTime, LastDraw;

function GameLoop()
{
  Now = Date.now();
  ElapsedTime = Now - LastDraw;
  
  if (ElapsedTime >= fpsInterval)
  {
    // Enough time has passed, time to draw.
    LastDraw = Now;

    // Do your drawing here.
  }
  
  window.requestAnimationFrame(GameLoop);
}
Attachments
yoss_controlling_framerate.js
(5.31 KiB) Downloaded 422 times

Dr. Madskull
Posts: 20
Joined: Tue Jun 04, 2019 11:35 am

Re: How to control framerate / lower cpu usage

Post by Dr. Madskull » Thu Aug 08, 2019 1:57 pm

Added some nice to have variables: jsStartTime, TotalPauseTime and TotalRunTime.

In a number of cases, it might be good to know the total time since the javascript started so I added it to this example code.

It's simple enough:

Code: Select all

TotalRunTime = Now - jsStartTime - TotalPauseTime;
jsStartTime is the start-time of the javascript.
TotalPauseTime records the total time the javascript is minimized and paused.
TotalRunTime is the time the javascript has been running, excluding the time it has been paused.

Example of usage could be for controlling which frame to show in an animation, simulations where time is important, I guess there is any number of uses!
Attachments
yoss_controlling_framerate.js
(6.21 KiB) Downloaded 428 times

Post Reply