Stop the ThreeJS rendering process

Currently, I am using ThreeJS to create a basic 3D scene with OrbitControls. The problem I'm facing is that it causes my entire website to lag, even when the user is not actively looking at the scene. I am in need of a function that can start and stop the rendering based on certain conditions, such as when the user is not viewing the canvas. Although I have a start function that works properly, the stop function does not seem to be functioning correctly, resulting in significant slowdowns after ThreeJS initializes.

Despite my efforts to find a solution, I have come across several potential fixes that do not seem to work with my specific application. It appears that these solutions may be outdated and incompatible with the current version of ThreeJS.

Below is an excerpt from my main.js file:

var scene, 
    camera, 
    controls,
    render,
    requestId = undefined;


function init() {
    scene = new THREE.Scene();
    var threeJSCanvas = document.getElementById("threeJS");
    camera = new THREE.PerspectiveCamera( 75, threeJSCanvas.width / threeJSCanvas.height, 0.1, 1000 );

    controls = new THREE.OrbitControls( camera );

    // Customize Controls and Camera settings

    // Generate Geometry.

}

function render() {
    requestId =  requestAnimationFrame(render);
    renderer.render(scene, camera);

}

function start() {
    render();
}

function stop() {
   window.cancelAnimationFrame(requestId);
   requestId = undefined;


}

In another JavaScript file, within the pageChange function of my multi-page application, there is a conditional statement as follows:

if (page == 5) { // The page containing the canvas
    if (!locationsRendered) {
    init();
    locationsRendered = true;
}
} else { // If the page does not have the canvas
    if (locationsRendered) {
        stop();
    }
}

The variable locationsRendered is initialized earlier in this secondary JavaScript file within the local scope.

I would greatly appreciate any assistance in resolving this issue, as it is crucial that this simple 3D scene does not cause lag throughout my application once it has been loaded. This situation is simply not practical.

Answer ā„–1

When your scene remains still, there is no need for an animation loop. The only time you need to update the rendering is when the camera moves as a result of a mouse or touch event.

Follow this simple pattern:

controls = new THREE.OrbitControls( camera, renderer.domElement );

controls.addEventListener( 'change', refresh );

function refresh() {

    renderer.render( scene, camera );

}

three.js revision 67

Answer ā„–2

I encountered a challenge with trackball controls in my scene, which prevented me from implementing the solution mentioned earlier (as trackball controls continue updating even after mouse events have finished).

To address this issue, I came up with the following solution:

function animate() {
  renderer.render(scene, camera);
  controls.update();
}
renderer.setAnimationLoop(animate);

This code snippet will keep the animation loop running indefinitely. To pause the animation, simply set the animation loop to null:

renderer.setAnimationLoop(null);        // pause the animation

To resume the animation, just reassign the animation loop to the animate function:

renderer.setAnimationLoop(animate);     // resume the animation

Answer ā„–3

One potential workaround to completely halting the rendering loop is to lower the frame rate, thus decreasing resource usage.

This strategy proves beneficial when seeking real-time updates on your display without active animation, as well as the ability to swiftly return to standard speeds when necessary.

By employing a basic setTimout() function, this goal can be efficiently attained.

const frameRate = 10;

function render() {

   //lower frame rate
   setTimeout(() => {

        requestAnimationFrame(render);

        //ensure rotation is enabled
        controls.update();
        renderer.render(scene, camera);

   }, 1000 / frameRate)

};

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

"Enhance your database by incorporating HTML link clicks through AJAX integration with PHP and MySQL

After browsing through similar questions and attempting to implement it on my website, I'm facing an issue where the expected functionality is not working as intended. When users click on a link, there is no response in the console, and the database r ...

Having trouble navigating to the link using Selenium WebDriver

I encountered an issue when trying to click on a link as it displayed an "Element Not Found" message. Below is the HTML code I used: <a id="expTo" class="formblue_link padRight10 exportLinkActive" style="display: block; margin-left: -50px; margin-b ...

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

https://i.sstatic.net/Ym7Uz.png I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(ne ...

Ensuring a consistently positioned footer at the bottom

I understand that this might not seem like a significant issue, but I'm encountering some difficulties. In my main.html file, there are three divs. The first div contains the navigation bar, the second div is an "empty" div that uses JQuery/Javascript ...

Limiting the data obtained from the API to extract only the desired values

Using an API, I am retrieving customer information and displaying it in the console. The code snippet used for this operation is: if (this.readyState === 4) { console.log('Body:', this.responseText); } }; This returns a JSON object with v ...

Tips for organizing the router.js file in VueJs

With my router.js file currently reaching around 500 lines, Iā€™m looking for a better way to structure it. { path: "/", component: () => import("./../src/views/dashboard/Dashboard.vue"), meta: { auth ...

Button for navigating to the previous slide on a Jquery slider

There appears to be an issue with the code on the previous button. When the user presses "previous" on the first slide, there is a momentary blank slider before the last slide appears. Is there a way to make this transition smoother? Thank you for your a ...

Having trouble with textures when using THREE.TextureLoader instead of the outdated THREE.ImageUtils.loadTexture?

Recently, I utilized a function to apply texture on a Cylinder shape. function createElementMaterial() { THREE.ImageUtils.crossOrigin = ''; var t = THREE.ImageUtils.loadTexture( IMG_MACHINE ); t.wrapS = THREE.RepeatWrapping; t.wr ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

Guide to retrieving fresh information from an API using a desktop application built on node and electron

Looking for advice on efficiently retrieving new order data from the Shopify API for a private desktop application I'm working on. Should I query the API at regular intervals while the application is active, or is there a way to implement webhooks in ...

Insert text into the cursor location within Summernote using JQuery

Currently, I am working on a flutter application where I have implemented the summernote editor using JQuery. ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); String txtIsi = data.text .replaceAll("'", '\&bsol ...

Understanding the distinction between assigning a value and setting text through JSE in Selenium using C#

Utilizing the IJavaScriptExecutor to set the attribute value can sometimes result in the text box containing the set value, but not displaying it as text. In some cases, the input is sent normally to certain text boxes, while for others, it is only setting ...

Manipulate a JavaScript object with AngularJS - viewing and editing capabilities

I'm looking to create a dynamic list of objects where clicking on an entry displays the object details and an edit button. When clicking on the edit button, the details should disappear and a form for editing the object should appear on the right side ...

I am unable to pass the req.params.id value as an input to a function located in a separate file

In my project, I've developed a REST API for user and coupon management. The main file driving this API is called coupon-api.js. This file contains the route definitions, while the functions to handle these routes are separated into two distinct files ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

Sending data from express js to a different server

Currently, I am faced with a scenario where I need to send a file from Jquery to my Express server and then transfer that request to another server without parsing the file in the Express server. Below are the code snippets I have been using so far: Jquery ...

Press on any two table cells to select their content, highlight it, and save their values in variables

I have a table retrieved from a database that looks like this (the number of rows may vary): |Player 1|Player 2| ------------------- |Danny |Danny | |John |John | |Mary |Mary | My goal is to select one name from each Player column and sto ...

Transitioning to Meteor and React or Immigrating to Meteor

Are there any available resources specifically designed for Meteor that can assist with loading large assets (ranging from 20MB to 80MB) primarily for offline use? Currently, I am working on a project using Vanilla JS on the client side, but I am contempl ...

Inserting documents into an array of objects in MongoDB

I am facing challenges while attempting to insert multiple objects into an array of objects in my development. The issue arises when trying to add more than one object with the same structure but different content. This is the structure of the groups coll ...