Unintended repetition with fetch() for loading a texture

I've been experimenting with using the fetch statement to fetch a local image and incorporate it into my (three.js) project. However, I seem to have created an infinite loop and I can't figure out why.

Since the project is quite large, I've included the relevant code snippet here:

var mesh;

function fetch_img(filename) {

    fetch(filename).then(function(response) {

        if (response.ok) {

            return response.blob();
        }
        throw new Error('Network response was an error.');

    }).then(function(blob) {

        mesh.material.map.image.src = URL.createObjectURL(blob);
        mesh.material.map.needsUpdate = true;

    }).catch(function(error) {

        console.log('Fetch failed because: ' + error.message);
    });

}

function start() {

    var material = new THREE.MeshBasicMaterial({

        map: new THREE.TextureLoader().load('loading.jpg', function(texture) {

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

            fetch_img('test1.jpg');
        })
    });
}

The concept behind this implementation is to display a 'loading' image first, and then switch to the actual image once the scene is created and loaded. I plan to call fetch_img() from multiple locations based on user input.

I suspect that my issue lies in my attempt to grasp JavaScript Promises. Can someone guide me in the right direction?

Answer №1

Let's break down what's going on:

When working with THREE.TextureLoader, it utilizes THREE.ImageLoader. Inside THREE.ImageLoader, an img element is created, with an assigned onload event listener. The img.src is then set to the provided URL.

Each time a new value is given to the image.src property, the event is triggered and sent to its handler, which still corresponds to the anonymous function specified in the THREE.TextureLoader definition.

And so, the cycle continues.

To resolve this issue, generate a new image, set its URL to the src property, and subsequently replace the entire map.image with this fresh image.

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

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

AngularJS: updating a module

I recently started learning AngularJS and I need some guidance on how to refresh the data in a table within a module (specifically, a list of names and post codes). Below is the script where I am trying to reload the JSON file upon clicking a button: < ...

Securing a namespace using passport js: A step-by-step guide

Imagine I have set up a specific route with the following namespace: app.use('/registered', userRoute); Recently, I wrote the following passportjs function: app.get('/logged/dashboard', function (req, res) { if (req.user === undefi ...

Inserting star ratings into a MySQL database using a form and AJAX request

I am in the process of creating a feedback application for a tablet using phonegap-android. The main page features a registration form, while the secondary page includes a star rating with six questions that the user needs to rate. I aim to store the resul ...

Issue with printing data consecutively using Javascript

My JavaScript code aims to display the content of the body tag again when the add button is clicked. The purpose is to add authors, with each author being added in sequence. For example, if there is only 1 author present, the user simply selects whether th ...

What is the best way to collaborate and distribute local npm packages within a shared repository across different teams?

Unique Scenario Imagine the structure of a folder as follows: /my-app /src /dist /some-library /src /dist package.json my-package.json Two npm packages are present: one for my-app and one for some-library. my-app relies on some-library. ...

PointerLockControls maintains a constant speed without slowing down (threejs)

I have integrated THREE.PointerLockControls into my project following the implementation demonstrated in this example (view code). The code seems to be accurately translated from the example, but I am facing issues with deceleration of the controller once ...

"After clicking the button for the second time, the jQuery on-click function begins functioning properly

(Snippet: http://jsfiddle.net/qdP3j/) Looking at this HTML structure: <div id="addContactList"></div> There's an AJAX call that updates its content like so: <div id="<%= data[i].id %>"> <img src="<%= picture %&g ...

Provide props to vue-router along with boostrap-vue's b-nav-item

I am currently in the process of transitioning my SPA from modals that load components to routed pages that load components. I have been able to successfully open a page using to="/fixtures" in the html, but I am facing an issue with passing in a component ...

AngularJS Large file size

After successfully building the 5 MIN QUICKSTART app, I decided to minify it with webpack following the recommendations in the angularJS docs. To my surprise, the size of the minified AngularJS file turned out to be approximately 700 KB, which is significa ...

The header() function triggers automatic page redirection instead of waiting for the form to be submitted

When I created a form that automatically sends an email upon submission, my goal was to direct the user to a thank you page after the email is sent. In my search for a solution, I stumbled upon the header() function in php and attempted to use it with the ...

Submitting information to the server utilizing a POST request through jQuery

What I'm attempting to achieve: I am currently working on sending data to my server using the $.post jQuery shortcut. The issue at hand: It seems that my program is not entering my switch case, possibly due to a problem with sending the action prop ...

The property linerGradiant of r cannot be destructured because it is not defined

I encountered the error "Cannot destructure property linerGradiant of r as it is undefined" during runtime, making it difficult to debug. The issue seems to stem from the compiled JS file, which is hard to read. The function is defined as follows: functio ...

Trouble with getting started on the Google Sheets API (v4) tutorial

I'm currently working my way through a tutorial that can be found at the link below: https://developers.google.com/sheets/api/quickstart/nodejs# When I reach the step of running the quick start file (node quickstart.js), I encounter the following err ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

ng-repeat not functioning properly when using track by, filter, and orderBy

I have come across this code snippet. http://jsfiddle.net/0tgL7u6e/ Scripting in JavaScript var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.nameFilter = ''; $scope.contacts = [ {name: 'G ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

URL not functioning properly on Django CMS menu

After setting up django-cms and creating a collapsible menu with categories and subcategories, I encountered an issue. When clicking on a main category, the URL appears correct but it does not navigate to the corresponding page. Main categories without chi ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...