The 3D cube in Three.js gains momentum with each re-initialization, spinning faster and faster

I'm puzzled by a phenomenon with the first Three.js example: the spinning 3D cube spins faster and faster every time it is re-initialized.

The code consists of an init function that sets up the scene and an animate function that kicks off the animation loop. Despite my expectation that the cube should reset completely when I repeatedly call init and animate, it actually spins faster each time it is re-initialized.

  • What could be causing this?
  • Is the object not properly re-initialized?
  • Is this a feature of three.js or JavaScript?

Check out this JS Fiddle demonstration of the issue, where the cube is re-initialized every two seconds: http://jsfiddle.net/1hq2esLr/ (tested in Firefox and Chrome)

Below is the complete code snippet:

var camera, scene, renderer,
    geometry, material, mesh;

function init() {
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.z = 1000;

    geometry = new THREE.BoxGeometry( 200, 200, 200 );
    material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );

    // The render area is simply a <div id="render-area"></div>
    var renderarea = document.getElementById('render-area');

    // Clear all existing nodes.
    while (renderarea.firstChild) {
        renderarea.removeChild(renderarea.firstChild);
    }
    renderarea.appendChild( renderer.domElement );
}

function animate() {
    requestAnimationFrame( animate );
    render();

}

function render() {
    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;

    renderer.render( scene, camera );
}

// Repeatedly calling this function seems to accelerate the spinning cube. Could this be due to a global variable issue?
function start() {
    init();
    animate();
}

Answer №1

When you call the start function a second time, your previous scene is not properly disposed of. As a result, you may see multiple scenes rendered on top of each other, giving the illusion that your mesh is moving faster. This happens because the animate function keeps calling requestAnimationFrame(animate), preventing any objects referenced by animate from being garbage collected.

To solve this issue, you can cancel the animation:

var id = null;
function start() {
    if (id !== null) 
        cancelAnimationFrame(id)   
     ...
}

function animate() {
    id = requestAnimationFrame(animate);
    render();
}

By implementing this solution, your objects will properly go out of scope and be handled by the garbage collector.

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

Refreshing DataTables with specific parameters using ajax.reload()

In my Angular2 project, I am utilizing DataTables with the serverSide feature. After making changes, I am attempting to reload the table and pass these changes as parameters in a POST request via AJAX. The issue I am encountering is that DataTables alway ...

What methods do Google and Yahoo use to update the URL displayed in the browser's status bar?

Have you ever noticed that on Google and Yahoo search pages, the URLs of the search result links actually point to google.com or yahoo.com? It's a clever trick they use by adding extra arguments to the URLs that allow for redirection to the actual sea ...

Creating a button that allows updates without refreshing the page can be achieved by implementing

Here are the items I have: <table> <tr> <th> id </th> <th> name </th> <th> update </th> </tr> <tr> ...

User update function is not being triggered by Ionic 2 Express call

I am currently working on implementing a feature in my Ionic 2 program that updates a user field when triggered. The code snippet below is from my user-service.ts file: // Update a user update(user: User): Observable<User> { let url = `${this.u ...

Traverse Through Collection of Vue Elements

I am working on creating an array of Vue Components based on a configuration file containing various UI sections to display; const config = [ 'summarySection', 'scoreSection', 'educationSection' ] I am attempting to ma ...

Looking to retrieve an element from an array of objects based on consecutive object properties, I have a specific value to search for

const levels = [ { indexId: 'A', level: 1, name: 'A', parent: '0', }, { indexId: 'A-A1', level: 2, name: 'A1', parent: 'A', }, { ...

Unable to showcase information in the center of an HTML document

Hello, I'm facing an issue with my HTML page that has a left vertical nav-bar. Despite my efforts, I can't seem to display content (text) in the center of the page as shown in the screenshot with the red oval. I've attempted inserting text ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Despite being deployed on Vercel, the process.env variables in Nextjs are still not functioning as expected

I'm currently working on a project that involves using 4 api keys that I need to keep hidden: STORYBLOK_API_KEY= EMAILJS_SERVICE_ID= EMAILJS_USER_ID= EMAILJS_TEMPLATE_ID= All of these keys are being accessed using process.env.XXX. What's inte ...

What purpose does the renderer.setSize function serve?

Can anyone help me understand how to adjust screen resolutions in three.js? I've been struggling to grasp the concept of the method "renderer.setSize();" and haven't found a clear explanation in the official documentation. The information provid ...

Learning the process of using JavaScript to extract data from a JSON file containing arrays

Currently grappling with the challenge of reading a JSON file using JavaScript. Unsure if my JSON file is in the correct format with arrays, but here is what I have. [ { "passageNumber":"2.3.1", "title":"Inside and out: A bronze ...

The Protractor element appears to be detached from the page's document

Currently, I am facing a challenge while using protractor in my Angular6 Project. The issue revolves around clicking elements within the project. Situation: Within a table row, there is a list of elements that I need to click on individually. Challenge: ...

JQuery is not able to render Hindi content properly

I am attempting to showcase some Hindi words using JQuery because these are essential contents that need to be displayed on every page of the website. Please note that this is a static website built with HTML and JQuery/JavaScript. Below is my JS file: in ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops mov ...

Incorporate a distinct, unique value from a JSON dataset into each iteration of the .each statement

My code includes an each statement that looks like this: $.each(data, function(i, value) { sublayers.push({ sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "=&ap ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Refresh the texture mapping within ThreeJS

Hey there! Just wanted to share that I was able to find a solution by using mesh.material.map.image.src = texture; Here was the original question: I'm working on a ThreeJS project and I'm trying to change the texture on a mesh. Unfortunately, I ...