When Three.js is calculating the elapsed time, it fails to render

My goal is to display a rotating cube with a consistent rotation speed across different machines. In order to achieve this, I calculate the timespan between each frame and use this elapsed value in the rotation process.

Here's the basic code snippet:

var elapsed = (timestamp - lastFrameTimestamp)/1000.0; // Issue with cube not showing up

However, when I use this calculated value, nothing appears on the screen. Surprisingly, there are no errors or warnings shown in the console. When I log the elapsed value to the console, it shows the correct number.

I experimented by setting the difference to a fixed value, like so:

var elapsed = 16.665487/1000.0;

The cube displays properly using this fixed value. I have created a jsFiddle for reference. I tested this issue in both Chrome and Firefox, but encountered the same problem in both browsers.

If anyone has any ideas or insights into what might be causing this issue, I would greatly appreciate the help!

Answer №1

One issue with the provided code snippet is that the variable timestamp will be initially set to null when the function animate is first called. As a result, both lastFrameTimestamp and elapsed are also set to null, impacting the rotation of the animation.

According to the information from MDN web docs regarding requestAnimationFrame:

The callback method receives a single argument, a DOMHighResTimeStamp, indicating the time when callbacks queued by requestAnimationFrame start executing. Despite the passage of time during previous callback executions in the same frame, each callback receives the same timestamp. This timestamp is represented as a decimal number in milliseconds but has a precision of at least 1ms (1000 µs).

Hence, requestAnimationFrame provides the callback function (animate) with a timestamp representing the current time (as returned by performance.now()) when it starts invoking callbacks.

To ensure your animation utilizes timestamps effectively, it's essential to initiate your animation loop by calling:

requestAnimationFrame(animate);

Instead of simply relying on animate();

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

When an image is opened in a modal, it causes the original image on

I recently created a website using HTML/CSS and JavaScript, and I incorporated a modal using Bootstrap 5. To add a unique touch, I used JavaScript to replace the standard "Save changes" button of Bootstrap with a random image inside the modal. However, I n ...

Clear the history of a dynamically generated button using jQuery

Greetings fellow StackOverflow users! I'm currently tackling a project that requires jQuery to implement a master/detail table layout in asp.net C#. The master and detail tables need to be generated dynamically. The issue I'm facing involves gen ...

Enhance the sequence of tweens by triggering them sequentially in response to rapid UI events

I am currently working on my three.js app setup and I am facing a challenge with creating a smooth transition between two models. The desired effect is to have the first model quickly scale down to zero, followed by the second model scaling up from zero t ...

Error message: CORS policy prevents third-party scripts from running in Next.js

I am encountering an issue with implementing a script handling tool in my Next.js project. I followed the documentation on nextjs.org and utilized the worker (experimental) parameter to enhance the page's performance. However, I am facing a CORS polic ...

Unlocking the potential of the post method in express.js by harnessing the power

I'm a beginner in JavaScript and Express JS. Currently, I am working on posting the user's current location from my Leaflet map and using that location as a query parameter to retrieve nearby restaurants. Below is an excerpt of my server code: co ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

Calculating the factorial of a number using the reduce function

I've been working on a function to find the factorial of an integer and then reducing the array containing factorials (multiplying each element). For instance: factor(5) >>> [1, 2, 3, 4, 5] >>> 1 * 2 * 3 * 4 * 5 >>> 120 v ...

Disable the ability for new windows, such as popups, submit buttons, and forms with the target set to blank, to reference

Encountering an issue, I stumbled upon some solutions here and on various other websites that I would like to share with you. The Problem: The window.opener functions of child pages stopped working after some security updates in modern browsers around 202 ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Utilizing Custom Script Tag Types in Visual Studio for Enhanced HTML Template Functionality and Improved Syntax Highlighting

Currently, I am utilizing Visual Studio 2012 for editing HTML and JavaScript. My approach involves inserting templates using partial views in inline script tags (view code below). The use of AngularJS, a Javascript framework, dictates that the type must be ...

Which specific page initiates the post request?

Seeking help with my post request that originates from a specific page on my website: reqdata = 'text=' + mytext; $.ajax({ type: "POST", url: "/request.php", data: reqdata, cache: false, success: function(html) { alert(html) } ...

Using Puppeteer to cycle through a CSV file and take a screenshot for each individual row?

I am looking to automate screenshotting URLs from a CSV file using puppeteer, but the current code execution is slow as each request waits for the previous one to finish. const csv = require('csv-parser'); const fs = require('fs'); con ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...

Handling TextChanged Event of a TextBox in ASP.NET using C#

I'm currently designing a POS screen that allows barcode scanning directly into a textbox. I want to implement a code behind procedure that adds the barcode-related data to the grid as soon as the textbox text changes. This is how my textbox looks: &l ...

Incorporate HTML into a webpage using JavaScript along with variables

So, I need to dynamically add and remove content to an HTML page with complex styling and data sets that will change based on the clicked element. An example scenario could be like this... <li class="foo"> <div class="slider" data-one="foo" d ...

What is the best way to retrieve nested reference data all at once from a Firestore document?

I have two distinct collections stored within my Firestore database. The first collection is users, and it can be visualized as shown here: https://i.stack.imgur.com/AKlyM.png The second collection is posts, represented by the following structure: http ...

Encountering a problem when trying to set the value in the controller and receiving unexpected output from the console

Attempting to assign a value to an object and show it in the view, but encountering an issue. When setting the vm.order.info.when to 'Any Value' and logging the vm.order.info, the value appears correct at first glance. However, upon inspecting th ...

Navigating to and Revealing a Division by Clicking

Check out this code snippet: <a onclick="$('a[href=\'#tab-customtab\']').trigger('click');">Enquire Now</a> <div id="tab-customtab"></div> This piece of code triggers the opening of the #ta ...

Removing CSS from a Link in react-router-dom

My attempt to create unique divs for different pages using the code in my home.js didn't go as planned. <Link to="Subject1"> <Product title="The Lean Startup" image="https://images-na.ssl-images-amazon.co ...

Displaying a variable in a text box using the italicized format

Could you please share how to display a variable in a textbox using italics style? Appreciate your help! ...