How can we pause rendering in three.js when the user's view of the 3D space is obstructed?

I am creating a spinning globe render that I would like to pause when the user is not viewing the dom element containing the renderer. This is important because unnecessary resources are being used when the user cannot see this specific part of the page. Here is what I have implemented so far—

window.addEventListener('scroll', () => {
    let scrollPosition = document.body.scrollTop;

    //element is almost visible, start rendering
    if (scrollPosition >= topOfElement - 200) {
        if (everythingIsLoaded && !isRendering) {
            render();
            console.log('render has been started');
        } else {
            //wait until everythingIsLoaded is true
        }
    //element is not visible, stop rendering
    } else {
        //need to stop rendering here!
        //this doesn't work, don't know how to do this
        if (animationFrame) {
            stopRendering(render);
            console.log('render has been halted');
        }
    }
});

Here is my render() function—

const render = () => {
    animationFrame = requestAnimationFrame( render );
    sphere.rotation.y += 0.001;
    renderer.render( scene, camera );
    isRendering = true;
};

Is there a way to effectively halt the render when the webGL region is out of view?

I attempted something like this in the code above—

var stopRendering = (af) => {
    cancelAnimationFrame(af);
    isRendering = false;
};

However, this does not actually seem to stop the render process at all.

Answer №1

window.cancelAnimationFrame is a method that takes the ID provided by window.requestAnimationFrame. In this case, the ID is stored in a variable called animationFrame. This function works similarly to setTimeout and clearTimeout.

Currently, you are passing the entire function reference render() to it. It's difficult to keep track of your usage of global variables based on the code shared, but most likely you should use:

if (animationFrame) {
    stopRendering(animationFrame);
}

This is because you have assigned the ID returned by requestAnimationFrame to the animationFrame variable in your scenario.

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

UnknownReferenceError: jwreload has not been declared (Exploring dynamic routing in next.js)

Error in dynamic route with next.js Recently, I started learning next.js and encountered an issue while implementing a dynamic route. The error message "ReferenceError: jwreload is not defined" keeps appearing whenever I reload the page. Surprisingly, des ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

Steps for transforming a regular string into a template string

Consider the following scenario: var data = '{"message": "`${message}`"}'; var obj = JSON.parse(data); var templateValue = obj.message; //`${message}` var message = 'hello'; What is the best way to evaluate the ...

Can you show me how to divide a number by a comma after every two digits and then save the result into two separate

Given a variable var Number = 2425;, the task is to split it into two parts and store them in separate variables. var data = 24; var month = 25; What would be the most efficient way to achieve this using JavaScript? ...

Using Three.js to generate shadows utilizing MeshFaceMaterial

I've been experimenting with different types of lights such as Directional, Spot, and Point, but none seem to cast a shadow on MeshFaceMaterial objects. Instead, the MeshFaceMaterial object just turns black. Check out my Test Website (please note tha ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

Switching the cursor to the following input after a paste event using JQuery

I am currently working on an HTML form that consists of multiple input boxes. I'm looking to focus on the next input box after pasting content into one of them. Below is the code snippet I have been using: $("input").bind('paste', function( ...

Creating a React Component in TypeScript that utilizes Promise Objects for data handling

After receiving a Promise type Object as a response, an error has been encountered: Error: Objects are not valid as a React child (found: object with keys { key1, key2, key3 ...}... How can this issue be resolved? // Component.tsx import React, { us ...

Guide to presenting XML information from a web address using XSLT

I am currently working with dynamic XML sports data from a URL in a Yahoo API, and I want to display and sort a selection of this data on my website using XSLT. This is my first time dealing with XML and XSLT, and while testing, I have managed to correctly ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Saving an array of key-value pairs in local storage

I'm attempting to save an array in local storage using the following code: var tempval = []; tempval['key'] = 1; localStorage.setItem("Message", JSON.stringify(tempval)); However, when I check local storage, it only sho ...

retrieving the values listed on the current v-data-table page

In my vuejs2 project, I am utilizing a v-data-table to display information in columns about a large number of users. Each page shows 25 users, with a total exceeding 60,000 individuals. I am wondering if there is a way to retrieve the list of users curre ...

Problem with single-table layout in DynamoDB and constraints on query parameters

I'm trying to limit the elements I fetch in each query, but encountered an issue: Using the single-table design in DynamoDB, I am only getting four items. https://i.sstatic.net/N4wVS.png If I check the first 10 elements in DynamoDB, I always get a ...

Determine the total amount of vertices being rendered using WebGL

Is there a method in the WebGL API to calculate the total number of vertices displayed on a specific canvas? I have come across certain tools that claim to provide this information, but some seem to produce inaccurate results (e.g. Three.js' renderer. ...

Acquiring exclusive files from Laravel 8 storage directory using JavaScript

I find myself in a specific situation: Working with a Laravel 8 application. My users upload STL files, which are stored in the storage/app/users/{userid} directory. These STL files are private and not accessible to everyone as they are not located in the ...

Error: The method 'text.substr' is not a valid function

Seeking assistance with creating a reusable component for implementing a readmore function in my application. I've encountered an issue that I can't seem to figure out. Could this be a specific feature of NextJS? Any insights or suggestions would ...

I need a counter in my React application that is triggered only once when the page scrolls to a specific element

I've encountered a challenge with a scroll-triggered counter on a specific part of the page. I'm seeking a solution using React or pure JavaScript, as opposed to jQuery. Although I initially implemented it with states and React hooks, I've ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Uncovering the Mystery: The Issue of Duplicate Items When Writing Arrays to localStorage in JavaScript

Struggling to create a Javascript quiz for my coding bootcamp. I'm facing challenges with retrieving and saving previous high scores from local storage. Can someone explain why the newScore is being written TWICE to the highScores arrayItems array in ...

What causes objects to be added to an array even when the condition is not met?

In the process of creating a terminal game using node.js, I am developing a random field consisting of different elements such as hats, holes, and pathways. The player's objective is to navigate through the maze and locate their hat within the field. ...