search
HomeWeb Front-endJS TutorialHow to control fps using requestAnimationFrame?

如何使用 requestAnimationFrame 控制 fps?

The word fps is usually associated with videos and games where we need to use animation. fps is the abbreviation of frames per second and represents the number of times the current screen is re-rendered.

For example, a video is a continuous row of images. This means that it displays images at very short intervals so the user has no way of knowing that it is displaying images individually. If we lower the fps of the video, it may look like an image animation instead of a video. Therefore, higher fps gives better results. Basically, fps tells us how many times in a second the screen should be updated.

Sometimes, we need to use JavaScript to control fps. There are different methods we can use, which we will learn in this tutorial.

Use the SetTime() function

The setTimeout() function takes the callback function as the first parameter and the time interval as the second parameter. Here we can control fps by re-rendering the screen after each time interval.

grammar

Users can use the setTimeout() function to control fps according to the following syntax.

setTimeout(() => {
   requestAnimationFrame(animate);
}, interval);

We used the requestAnimationFrame() method to call the animate() function in the above syntax.

step

  • Step 1 - Define the totalFrames variable and initialize it to zero. It will record the total number of frames.

  • Step 2 - Additionally, define the fps variable and store the value of fps.

  • Step 3 - Define intervalOffps variable and store intervals into it. It stores 1000/fps where 1000 is milliseconds and we get the time interval by dividing it by fps.

  • Step 4 - Store the current time in the startTime variable.

  • Step 5 - Call the animate() function.

  • Step 5.1 - Call the requestAnimationFrame() function using the setTimeout() function after each internvalOffps.

  • Step 5.2 - In the callback function of the setTimeout() function, the user can write code to re-render the screen or draw shapes on the Canvas.

  • Step 5.3 - Use a Date() object and get the current time. Subtract the start time from the current time to get the elapsed time.

  • Step 5.4 - Using math functions, get the total fps and total time.

Example 1

In the following example, we use the setTimeout() function to control fps. We use "3" as the value for fps. Therefore, our fps interval is equal to 1000/3. Therefore, we will call the requestAnimationFrame() method every 1000/3 milliseconds.

<html>
<body>
   <h3 id="Using-the-i-setTimeOut-method-i-to-control-the-fps-with-requestAnimationFrame"> Using the <i> setTimeOut() method </i> to control the fps with requestAnimationFrame </h3>
   <div id="output"> </div>
   <script>
      let output = document.getElementById("output");
      // Initial frame count set to zero
      var totalFrames = 0;
      var current, consumedTime;
      
      // Set the fps at which the animation will run (say 10 fps)
      var fps = 3;
      var intervalOffps = 1000 / fps;
      var AfterTime = Date.now();
      var starting = AfterTime;
      animate();
      function animate() {
         setTimeout(() => {
         
            //  call the animate function recursively
            requestAnimationFrame(animate);
            
            // get current time
            current = Date.now();
            
            // get elapsed time since the last frame
            var elapsed = current - starting;
            
            //Divide elapsed time with frame count to get fps
            var currentFps =
            Math.round((1000 / (elapsed / ++totalFrames)) * 100) / 100;
            output.innerHTML = "Total elapsed time is equal to = " + Math.round((elapsed / 1000) * 100) / 100 + "<br>" + " secs @ ";
            output.innerHTML += currentFps + " fps.";
         }, intervalOffps);
      }
   </script>
</body>
</html>

Using the Date() object

We can use the Date() object to get the difference between the current time and the previous frame time. If the time difference exceeds the frame interval, we will re-render the screen. Otherwise, we wait for a single frame to complete.

grammar

Users can use the time interval to control the frame rate according to the following syntax.

consumedTime = current - AfterTime;
if (consumedTime > intervalOffps) {
   // rerender screen
}

In the above syntax, the elapsed time is the difference between the current time and the time when the last frame was completed.

Example 2

In the example below, we take the time difference between the current frame and the last frame. If the time difference is greater than the time interval, we re-render the screen.

<html>
<body>
   <h3 id="Using-the-i-Date-object-i-to-control-the-fps-with-requestAnimationFrame"> Using the <i> Date() object </i> to control the fps with requestAnimationFrame. </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      // Initial framecount set to zero
      var totalFrames = 0;
      var current, consumedTime;
      
      // Set the fps at which the animation will run (say 10 fps)
      var fps = 50;
      var intervalOffps = 1000 / fps;
      var AfterTime = Date.now();
      var starting = AfterTime;
      animate();
      function animate() {
      
         // use date() object and requestAnimationFrame() to control fps
         requestAnimationFrame(animate);
         current = Date.now();
         consumedTime = current - AfterTime;
         
         // if the consumed time is greater than the interval of fps
         if (consumedTime > intervalOffps) {
         
            // draw on canvas here
            AfterTime = current - (consumedTime % intervalOffps);
            var elapsed = current - starting;
            
            //Divide elapsed time with frame count to get fps
            var currentFps =
            Math.round((1000 / (elapsed / ++totalFrames)) * 100) / 100;
            output.innerHTML = "Total elapsed time is equal to = " + Math.round((elapsed / 1000) * 100) / 100 + "<br>" + " secs @ ";
            output.innerHTML += currentFps + " fps.";
         }
      }
   </script>
</body>
</html>

Example 3

In the example below, the user can set the fps using the input range. Afterwards, when the user clicks the button, it executes the startAnimation() function, which sets the fps interval and calls the animate() function. The animate() function calls the drawShape() function to draw shapes on the canvas and control fps.

Here, we use some methods to draw shapes on the canvas. Users can use the input range to change the fps, try animating shapes and observe the difference in animation.

<html>
<body>
   <h3 id="Using-the-i-Date-object-i-to-control-the-fps-with-requestAnimationFrame">Using the <i> Date() object </i> to control the fps with requestAnimationFrame. </h3>
   <!-- creating an input range for fps -->
   <input type = "range" min = "1" max = "100" value = "10" id = "fps" />
   <button onclick = "startAnimation()"> Animate </button> <br><br>
   <!-- canvas to draw shape -->
   <canvas id = "canvas" width = "250" height = "250"> </canvas>
   <script>
      let canvas = document.getElementById("canvas");
      let context = canvas.getContext("2d");
      let animation;
      let intervalOffps, current, after, elapsed;
      let angle = 0;
      // drawing a sha[e]
      function drawShape() {
         context.save();
         context.translate(100, 100);
         
         // change angle
         context.rotate(Math.PI / 180 * (angle += 11));
         context.moveTo(0, 0);
         
         // draw line
         context.lineTo(250, 250);
         context.stroke();
         context.restore();
         
         // stop animation
         if (angle >= 720) {
            cancelAnimationFrame(animation);
         }
      }
      function animate() {
      
         // start animation and store its id
         animation = requestAnimationFrame(animate);
         current = Date.now();
         elapsed = current - after;
         
         // check if elapsed time is greater than interval, if yes, draw shape again
         if (elapsed > intervalOffps) {
            after = current - (elapsed % intervalOffps);
            drawShape();
         }
      }
      function startAnimation() {
      
         // get fps value from input
         let fpsInput = document.getElementById("fps");
         let fps = fpsInput.value;
         
         // calculate interval
         intervalOffps = 1000 / fps;
         after = Date.now();
         requestAnimationFrame(animate);
      }
   </script>
</body>
</html>

The above is the detailed content of How to control fps using requestAnimationFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.