`Incorporate numerous models into a For Loop for efficient processing`

Currently, my goal is to:

  1. Retrieve a JSON file from the server that contains data regarding my models
  2. Utilize a PLY loader within a for loop to incorporate them into the scene
  3. Include them in an array

Below are the functions I've implemented:

function fetchJSON(callback) {
    var temp = $.getJSON("data/data.json", function(data) {
        //calling the callback function while passing the retrieved data
        callback(data);
    });
}

function loadModels() {

    //obtaining our JSON data
    fetchJSON(function(data) {

        //analyzing the received data

        nodes = data.library[0].model.nodes;

        nodesLen = nodes.length;

        //Loading nodes and adding them to the scene and array
        for (var i = 0; i < nodesLen; i++) {

            var url = nodes[i].url;

            // Instantiating a PLY loader
            var loader = new THREE.PLYLoader();
            loader.load(url, function(geometry) {

                geometry.computeFaceNormals();

                var material = new THREE.MeshPhongMaterial({ color: 0xffffff, vertexColors: THREE.VertexColors, transparent: true, side: THREE.DoubleSide });
                var mesh = new THREE.Mesh(geometry, material);

                mesh.stepNum = i;

                console.log(i);

                mesh.position.x = 0;
                mesh.position.y = 0;
                mesh.position.z = 0;

                //Adding to the scene
                scene.add(mesh);

                //Appending to the array
                nodesArr.push(mesh);

            });
        }

    });

}

Issue: The models are not loading as expected. Upon checking the output of "console.log(i)" inside the PLY loader, it consistently returns the same value. This suggests that another loop begins before the current one finishes. How can I ensure that the loop waits until all functions complete before initiating another iteration?

Answer №1

Exploring the concept further, it is essential to understand why this behavior occurs: JavaScript closure inside loops – simple practical example

The issue lies in the asynchronous nature of the function loader.load(), which means that the loop continues without waiting for responses from the network. By the time the loop finishes (where i equals nodesLen and all HTTP requests are triggered), none of the requests have completed. Only after a significant delay (microseconds vs hundreds of milliseconds) will the callback (function(geometry) {}) be executed.

An effective solution, as outlined in the provided answer, involves using closures to lock in the current value of i within the callback function. While this approach may resolve the issue, concurrent requests continue to execute (which can be manageable due to the browser's capabilities).

To address the primary concern of waiting for each request to complete before initiating the next one, consider implementing the following:

var remainingUrls = [ /* ... list of all model URLs ... */ ];

function loadNext() {
  // Retrieve and remove the first URL from the remaining URLs array
  var nextUrl = remainingUrls.shift();

  if (!nextUrl) {
    // End the process when no next URL is available
    return;
  }

  loader.load(nextUrl, function(geometry) {
    addToScene(geometry);

    // Proceed to load the next file
    loadNext();
  });
}

// Begin loading the entire list
loadNext();

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

Achieving Vertical Centering of Text in Bootstrap 5 Buttons with Flex Box to Prevent Overlapping Icons

How can I prevent the text on a Bootstrap 5 button with horizontally and vertically centered text, along with a right aligned icon, from overlapping when it wraps? Additionally, how do I ensure that the icon stays vertically centered when the button text w ...

What are some effective methods for troubleshooting unidentified JavaScript functions within Chrome's performance analyzer?

Currently, I am utilizing Angular 4 and incorporating numerous anonymous arrow functions (() => {}). I am curious if it is feasible to identify these functions in Chrome's performance analyzer without assigning them names. Below is an example of t ...

Is it possible to use two onChange functions in a single text field with ReactJS?

Is it possible to have two onChange functions in a single Textfield? In my code, "onChange={ showDiv}" is a handler that shows "Direct 2" when clicked and hides upon selecting option1. The second onChange={(e) => exhandleChange(e)} is used for another ...

Is it possible to incorporate an external javascript file in my CSS file?

Currently, I am attempting to create a setup where my background adjusts based on the width of the user's browser. However, I am constrained by a background specified in the external stylesheet under a specific element. While I have the ability to alt ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...

When utilizing data-ng-view, AngularJS struggles to locate the corresponding HTML content

I am currently working on building an application using AngularJS, MVC, and API. Below you can find the code for my AngularJS module and controller: //home-index.js var myApp = angular.module('myApp', []); myApp.config([function ($routeProvider) ...

Forever is causing email sending from the node server to fail

My API server is up and running with Node, featuring an add user function: add: function (userArray, onSuccess, onError) { userArray.forEach(function (user) { var length = 8, charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345 ...

Upgrading to Bootstrap 5 and customizing the collapse button text upon click

I've spent a lot of time searching for a solution to my problem, but all the advice I found is for bootstrap 3 and 4, not version 5. Below is the code I am currently using: <div class="p-3">9 Members Online <a class="p-1 btn ...

What are the steps to produce a high-quality WebP image without losing any data?

I recently started experimenting with the WebP image format in Chrome by utilizing the canvas element. After researching on MDN, I discovered that the toDataURL function has a second parameter that determines the quality of the resulting image. My goal is ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

Deleting outdated files in a temporary uploads directory - NodeJS best practices

My process for removing old files from a tmp upload directory involves the code below: fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); if (files.length > 0) { files.forEach(function( file ) { ...

The face textures are not being applied correctly to the model imported in THREE.js

I'm having trouble importing a model exported from blender using the THREEJS exporter. The model loads correctly in my scene with the materials applied, such as the car appearing yellow and the glass being transparent as intended. However, I am facin ...

Is it possible to utilize a JS script generated within the body or head of an HTML file directly within CSS code?

As a beginner in webpage development, I have a query regarding the technical aspect. Is it possible to utilize variables from a JavaScript function, which is placed either in the head or body of an HTML file, directly in CSS code to make modifications such ...

clicking on a link with the symbol "#" in the href attribute in Firefox prevents the setter

Good morning everyone, It's early Monday morning and I'm having trouble understanding why this particular line works in Internet Explorer but not in Firefox. <a class="button" href="#" onclick="setMaintenanceMode(false);">disable</a> ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

A declaration file in Typescript does not act as a module

Attempting to create a TypeScript declaration file for a given JavaScript library my_lib.js : function sum(a, b) { return a + b; } function difference(a, b) { return a - b; } module.exports = { sum: sum, difference: difference } my_lib.d.ts ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Tips for creating test cases for the following Angular method

Looking for advice on creating Jasmine unit test cases for a method that opens a custom type dialog in my component. export class OpenPopUpComponent implements OnInit { constructor(public dialog:NewCustomDialog) {} ngOnInit() { } open ...

Tips for identifying and swapping values/parameters in a URL during redirect

To provide more clarity on my inquiry, I will outline the details below: There are three links: Link A, Link B, and Link C Link A: {c_val} Link B: {id} Link C: In the database, there is a value adgaf7g6adf6gadfg8a86fgs9f6g The main focus here is when ...

Exploring the Differences between HTML Values in HTML and jQuery

Can someone assist me with comparing HTML values to check for equality? I am looking to compare the values of two select elements in HTML and needing guidance on how to accomplish this. Specifically, I want to determine if the selected values from both s ...