What is Window.requestAnimationFrame() in JavaScript?

Developers often use animations to make their web pages elegant and user-friendly. In JavaScript, programmers use the window.requestAnimationFrame() method of the window object to create animations.

This method generates animations that are in sync with the processing speed. It also slows down the animation's loading time when it is not in use, and saves the browser's resources while rendering web pages.

Syntax

Let's take a look at this method's syntax


window.requestAnimationFrame(callback);

Parameters

This method has a single parameter:

  • callback: This function creates the next frame of the animation. It takes a timestamp as an argument to make changes in the animation variables when they are rendered on the screen.

Return value

The return value of this method is a non-zero long integer, which is a unique identifier for the animation in the callback function.

Example

The code below demonstrates the use of the window.requestAnimationFrame() method:

Explanation

  • Lines 5–8: In this piece of code, we have a <div> tag that encapsulates the <img> and the <h4> tags that we want to animate.
  • Line 9–22: These lines contain <script> tags that enclose actual JavaScript code that depict the use of window.requestAnimationFrame(). We can further break them down as follows:
    • Line 10–11: We initialize a variable named start to null. We fetch the <div> tag by using document.getElementById() to apply the animation.
    • Line 12–20: These lines of code contain our self-defined function of startAnimation(). This method checks if the start variable is null using an if-statement. It then adds linear motion to the div tag using the style.transform property.
    • Line 18: Then, we use the translateX property of CSS and the Math.min() function to apply the animation accordingly.
    • Line 19: The window.requestAnimationFrame() method then passes the callback function startAnimation(), which renders the next frame.
    • Line 20: This line of code initiates the first call to the startAnimation() method and renders the animation as seen in the output tab above.

Note: To learn more about the Math.min() function, we can refer to this link.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved