What is the mechanism behind the workings of the requestAnimationFrame loop?

I'm currently studying the ins and outs of javascript and Three.js but I'm struggling to grasp the concept of how the requestAnimationFrame function operates. Could someone please break down the following code in simple terms for me?

( feel free to view the complete code on jsfiddle )

  // loop function
  function render(time) {
    time *= 0.001;  // conversion to seconds

    cube.rotation.x = time;
    cube.rotation.y = time;

    // rendering the scene
    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);

Answer №1

When using requestAnimationFrame(), the browser is asked to execute a function before repainting.

Check out requestAnimationFrame documentation

Here is the code snippet:

  function render(time) {    
    time *= 0.001;  // time converted to seconds

    cube.rotation.x = time;
    cube.rotation.y = time;

    // render the scene
    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
  • A time variable is set to change value with each call to render()
  • The rotation x and y values of the cube are set to the time variable
  • The scene is rendered with the updated properties
  • requestAnimationFrame is called within the render function, creating a loop that continuously repaints the cube on screen with updated coordinates
  • requestAnimationFrame is also called once outside of the render function for the initial rendering of the cube

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instantiate a child class within an abstract class by utilizing the keyword "this"

Within my code, there is an abstract class that uses new this(). Surprisingly, this action is not creating an instance of the abstract class itself but is generating an instance of the class that inherits from it. Even though this behavior is acceptable i ...

Looking for assistance with transferring a data attribute to a form redirection

I'm seeking assistance with a coding dilemma I've encountered. To provide some background, I have a list of items on my website, each featuring a 'Book Now' button that redirects users to different pages. Recently, I incorporated a mod ...

"Can you help me figure out how to transform a date string into a concise date object using JavaScript

As a newcomer to UI coding, I am faced with the challenge of working with date data from JSON in the format "2021-02-28 00:00:00". However, when writing to an xlsx file, I need the date to be in a different format rather than as a string. Here is my attemp ...

notifying users via email in a React application with data saved in Firebase database

In order to notify users of upcoming deadlines, I need to send an email when they are approaching. The deadline is saved in Firebase as a specific date and time (mm/dd/yyyy mm: hh), associated with the user's account email address ([email protect ...

The appearance of my website appears differently depending on the resolution

Just recently, I began exploring the world of HTML/CSS/JS and created a handy tool for my personal use. However, I encountered an issue when viewing it on different resolutions which caused some elements to look distorted. The tool I made allows me to inp ...

Image encoded in base64 not appearing on the screen

Hey there, I'm currently working on implementing a jQuery image uploader that generates a base64 code when an image is selected. function readImage(input) { if (input.files && input.files[0]) { var FR= new FileReader(); FR.onload ...

What is the process for forming a series of arrays from one singular array?

If I have a large array consisting of numbers from 1 to 18, is there a simple method to split it into pairs like [1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] for n=2? The special case of n=2 is all I need. ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

There was an AJAX post error that occurred due to the refusal to set an unsafe header with the name "Connection"

My custom ajax function sends data to a PHP file, but I'm encountering two errors each time the data is posted: Refused to set unsafe header "Content-length" Refused to set unsafe header "Connection" Here is my code: function passposturl(url1 ...

Methods for retrieving and persisting the data from a particular row within a table using JavaScript or jQuery

Is there a way to store the selected row values of a table in an array of arrays using JavaScript / jQuery? Check out this JSFiddle I believe that we should listen for the event when the 'Show selected' button is clicked. For instance, in Java ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

Incorporate a Variety of Elements onto Your Webpage

I have developed a custom tooltip plugin using JQuery, and I am implementing it on multiple A tags. Each A tag should have a unique tooltip associated with it, so I have the following code: var $tooltip = $("<div>").attr("id", tooltip.id).attr("cla ...

My script is unable to access the session variable

Two $_SESSION variables seem to be inaccessible in any script on my page, yet I can confirm their existence in the PHP code of the same page by using echo to display their values. When trying to display these $_SESSION variables in jQuery using the code b ...

Implementing a smooth transition effect on an ajax tab

I have a tab code that uses ajax data attributes to load content. The tabs are loaded with ajax from PHP code based on the data attribute. How can I add a fade in/out effect to the tabs' content? I've attempted it but haven't been successful ...

After extended periods of use, the website experiences frequent crashes

Currently, I am developing a website using a free provider (000webhost) and focusing on integrating a chat feature. To achieve this, I have implemented an interval every 500 milliseconds that reads a file to check for new messages. When a new message is de ...

Utilizing Node.js: How to access another function within the same controller?

I am facing an issue with accessing one function from another in my code. How can I achieve this? class firstController { firstFunction(req, res) { var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(n ...

How can I retrieve the name of the upcoming middleware function in Express.JS?

Hey there, I'm currently facing a challenge with retrieving the names of middleware functions in a specific request route. Let's consider the code snippet below as an example: const authorizeRoute = (req,res,next) => { let nextFunctionName = ...

Upon receiving the ajax request, the entire code page is called back

I'm having trouble saving data using a button in Laravel. When I use console.log, the entire code appears in the console and I don't understand why this is happening. Here is my input field and button: <form action="{{ url('sendcom& ...