OBJ and MTL Loaders from Three.js are not being continuously invoked

I'm currently using the THREE.js OBJ and MTL Loader in a loop to display various elements of a 3D animated cake. I specifically need these elements so that users can change the color of certain parts (e.g. decorations) of the cake.

However, I've noticed that every time I hit a THREE.load function, the loop execution is paused and it moves on to the next iteration (i++). As someone new to JavaScript, I'm unsure if I might be missing some basic understanding of loops.

It's only on the final iteration that the load function is called and executed correctly. If I run the same code without a loop, manually providing the material/object paths and using multiple loaders, everything works smoothly.

function draw(currentlySelectedCake){

layerArray = [];
// Load  Cake

var i;

for (i = 0; i < currentCakeElements.length; i++){

 if(currentCakeElements[i].endsWith(".mtl")){

    var materialPath = "uploads/" +currentlySelectedCake + "/" + currentCakeElements[i];
    var objectPath = "uploads/" +currentlySelectedCake + "/" + currentCakeElements[i+1];

    var cakeLoader = new THREE.MTLLoader();

    cakeLoader.load(materialPath, function (materials) {    
      materials.preload();

      // Load the Cake
      var objLoader = new THREE.OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(objectPath , function (object) {
        
      
        layer1 = object.clone();
        layer2 = object.clone(); 
        layer3 = object.clone();

        layer1.name = "Layer1Part" + i;
        layer2.name = "Layer2Part" + i;
        layer3.name = "Layer3Part" + i;



        layer1.traverse((child) => {
            if (child.isMesh) {
              child.material = child.material.clone();
            }
          });

          layer2.traverse((child) => {
            if (child.isMesh) {
              child.material = child.material.clone();
            }
          });

          layer3.traverse((child) => {
            if (child.isMesh) {
              child.material = child.material.clone();
            }
          });

        layer2.position.y = tortenhoehe;
        layer3.position.y = tortenhoehe*2*0.75;

     
        camera.lookAt(layer2.position);
        
        layer1Group.add(layer1);
        layer1Group.name = "Layer1";
        layer2Group.add(layer2);
        layer2Group.name = "Layer2";
        layer3Group.add(layer3);
        layer3Group.name = "Layer3";



    });

    layer1Elements.push(layer1Group);
    layer2Elements.push(layer2Group);
    layer3Elements.push(layer3Group); 
});


  }

  
  
});

}



} 

Answer №1

My proposed solution is in the final phase of testing and appears to be promising.

  1. Initialization of variables i and j precedes the loop
  2. An anonymous function is created within the first loop iteration
  3. Within the anonymous function, a reference to variable i is made outside of its scope
  4. Upon completion of the first loop, the value of variable i reaches 3 after running the loop thrice
  5. The second loop triggers the execution of functions created in the first loop
  6. During invocation, the interpreter detects the absence of i within the function
  7. As the anonymous function becomes a closure, the interpreter accesses the variable i in the global scope within its lexical scope
  8. With the value of i being 3, the issue identified in step 4 is resolved
  9. Therefore, the output will be 3
  10. Subsequent loops from the second to third iteration follow the same logic as steps 6 to 10

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

Troubleshooting issues with the controller functionality in AngularJS

The following code is not producing the expected output of 'Hello, World' output: {{ greetings.text }}, world Could someone please assist me in determining why it is not displaying 'hello, world' as intended <!doctype html> ...

The error message "Uncaught TypeError: Cannot read property 'length' of undefined" is commonly encountered in asp.net while using dataTables with zero config

I am encountering an issue with dataTables in my ASP.NET webforms application. The table is generated in the codebehind at Page_Load() and works fine on other pages, but for some reason, I am getting an error message on one specific page: "datatables.min.j ...

Ways to determine the position of elements when they are centered using `margin:auto`

Is there a more efficient way to determine the position of an element that is centered using CSS margin:auto? Take a look at this fiddle: https://jsfiddle.net/vaxobasilidze/jhyfgusn/1/ If you click on the element with the red border, it should alert you ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...

How can I use JavaScript to capture the "MDCMenu:selected" event for the Menu Component in Material Design Web Components?

I am currently using the Material Design Web Components plugin known as "Menu." Once the menu is launched, my goal is to be able to effectively handle all possible ways a "menu item" can be selected. While adding an on-click event through my framework&apo ...

How can you prevent the browser from prompting to save your email and password when filling out a sign-up form?

I'm currently developing a PHP sign up form, but whenever I click on the sign up button, the browser prompts me to save the email and password. Is there a way to prevent this from happening? ...

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

div.load() results in a complete page reload

When I save form data, my goal is to load only the specific div without refreshing the entire page. However, despite using the preventDefault() command, the form still seems to be posting the whole page. I have tried adding the following code: $("#btn ...

reinitializing the prototype object's constructor property

Let's analyze the code snippet provided: function shape(){ this.name = "2d shape" } function triangle(){ this.name = "triangle"; this.ttest = function(){ alert("in triangle constructor"); } } function equitriangle(){ thi ...

Using jQuery to import certain library causes the XPage to completely lock up

My XPage only relies on 2 js imports - one being JQuery and the other dependent on JQuery specifically for smart companies search in the Russian Federation. However, a challenge arises when trying to import the second library as it causes the entire page t ...

Changing state property upon clicking child element in React is not feasible

I am interested in changing the text color upon clicking it using a function triggered in a child element that affects the parent's state. This is because a specific property of the parent determines whether the text should be one color or another. W ...

Clicking on a row in the Gridview should trigger the expansion or collapse of the Nested

My current issue involves a nested GridView setup like this: <asp:GridView ID="gvParent" runat="server" DataKeyNames="id"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:GridView ID="gv ...

Jpicker is renowned for its transparency feature

I am currently using the Jpicker jpicker-1.1.6.js script which can be found at Below is a snippet of my code: <script type="text/javascript"> $(function() { $.fn.jPicker.defaults.images.clientPath='/img'; var ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...

removing functionality across various inputs

I have a JavaScript function that deletes the last digit in an input field. It works fine with one input, but not with another. It only erases the digit in the first input. <script> function deleteDigit(){ var inputString=docu ...

Make an AJAX GET call to an ASP.NET Web API endpoint

Here is the ajax script I am using: $.ajax({ dataType: 'json', url: url, data: tuDispId, type: "GET", success: function (data) { bindData(data); $("#ale ...

Updating Text within a Label with jQuery

Seeking assistance with a jQuery issue that I am struggling to resolve due to my limited experience. Despite attempting to search for solutions online, I have been unable to find an alternative function or determine if I am implementing the current one inc ...

Angular promise fails to resolve after an extended period of waiting for a response

My application is designed to send GET requests to my node/express server. In order to monitor changes in the server code, I have implemented a setTimeout function. While the promise function on the client side initially functions properly for a short peri ...

Determine the position of the anchor/hash in the document

I am really struggling here. Whenever I try to enter index.html#about (or bookmark it and open it), I need to extract the index() of this and place it in the script below as "slideNumber". HTML Structure <div id="slideshow"> <div id="frontp ...

Optimizing Three JS computeVertexNormals() for Improved Performance

I have a massive buffer geometry consisting of approximately 4 million vertices that requires a small area of shading to be updated. Currently, I randomly update the vertex normals causing lag. I attempted using updateRange.offset on the geometry but it se ...