calling requestAnimationFrame from within a freshly created instance

I'm encountering an issue with executing an animation. Specifically, this problem arises within var ob1 = function() {};. Once triggered, the animation runs for a brief period before I receive the error message

Uncaught RangeError: Maximum call stack size exceeded
. Interestingly, when the same structure is executed outside of the object, there are no complications.

/////////////// Enact the scene rendering ///////////////
this.render = function (){

        renderer.render(scene,camera);
        if(isControls == true) controls.update(clock.getDelta());
        this.animate();
        //console.log(true);
        requestAnimationFrame(this.render());
}

/////////////// Adjust objects during animation ///////////////
this.animate = function (){
        console.log("!");
}

Answer №1

To properly use requestAnimationFrame, make sure to pass a function reference instead of directly invoking the function:

requestAnimationFrame(this.render);

If you are utilizing this inside the render function, it is recommended to utilize bind:

requestAnimationFrame(this.render.bind(this));

Invoking the function as in your original code may result in a Stack Overflow due to synchronous self-calling until the call stack reaches its limit.


Answer №2

I found a clever solution to make this function run smoothly within a class by following an example I came across.

requestAnimationFrame(() => {
      this.animate()
})

It appears that this workaround resolves the issue effortlessly!

Check out my application of this technique in a threeJS scenario:

https://jsfiddle.net/gentleman_goat66/o5wn3bpf/107/

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

Searching for values in nested arrays using lodash.find

Presented below is an array where I aim to employ lodash for item search: [ { "itemA": "apple", "itemB": [ { "itemC": "1", "itemD": "red apple" }, { "itemC": "2", "itemD": "green apple" }, ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Tips for refining search criteria with a combination of checkbox and range slider in Angular 2

In an attempt to refine the results for the array "db," I have implemented three filters: price, duration, and category. I have experimented with using the filter() method to apply these filters. You can find the code I have worked on here: https://stack ...

Tips for simulating an ajax request in a Jasmine test

Check out my code snippet below: function sendRequestData(url, urlParameters) { $.ajax({ url : url, method : 'POST', headers : { 'Accept' : 'application/json' }, contentType : 'application/js ...

Troubleshooting: Why jQuery is Not Functioning Properly in Conjunction

Currently, I am in the process of developing a friend search feature. This function operates effectively; upon entering a name in the search bar, individual user profiles appear in separate div containers with their respective images and names. Each profil ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Issues persist with AJAX call to servlet

Recently, I encountered an issue with my servlet when attempting to insert form input fields into the database. The servlet was working fine when utilizing the following code: <form action="CreateUserServlet"> However, upon implementing some form v ...

What steps should I follow to ensure that the message "Read It" is logged to the console before "Ex It"?

app.get('/', async (req, res) => { await fs.readFile('./views/website/index.html', 'utf8', (err, d) => { data = d console.log("Successfully read the file") // console.log(data) ...

Is it possible to include a component in an HTML file when the constructor of the component needs a parameter?

Recently delving into the world of AngularJs has been a captivating experience for me. I am aiming to develop a component with a constructor that accepts a parameter of type string. However, when I try to declare the selector on the HTML file, the componen ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

What is the purpose of uploading the TypeScript declaration file to DefinitelyTyped for a JavaScript library?

After releasing two JavaScript libraries on npm, users have requested TypeScript type definitions for both. Despite not using TypeScript myself and having no plans to rewrite the libraries in TypeScript, I am interested in adding the type definition files ...

Distinguishing Response Headers in XMLHttpRequest and jQuery AJAX FunctionUniqueness:

Hello, I'm facing an issue that is not a duplicate. Here is the code snippet: var data = {'userId': window.cookie.get('userId'), 'sessionId': window.cookie.get('sessionId')} $.post(window.DbUrl + '/t ...

The dynamics of Express.js functionalities

I am seeking to better understand how flow functions within an Express app using Routes, with the following set of Routes: app.use(require('./routes/reportsRouter')); app.use(require('./routes/crewsRouter')); app.use(require('./ro ...

The React route fails to display until clicked upon

Struggling with integrating React Router into my Electron desktop app for navigation. During debugging, I realized that the login component, which doesn't use routers, transitions smoothly to a component with a router. However, this new component fail ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

Is there a way to assign multiple paths to a single page within the NextJS pages directory?

I'm currently working on a project that has two different themes, and I have the ability to switch between them based on the environment. Everything works perfectly, but I'm encountering an issue with paths. Some pages should open with different ...

Angular Bootstrap's tabs feature a powerful select() function that allows users to easily

Take a look at this where you can find a tab component. Within the tab settings, there are methods like: select() and deselect() I was unsure how to properly utilize them. I attempted to access them from my JavaScript file using $scope but encountered ...

How can Swiper efficiently display the next set of x slides?

After exploring SwiperJS at https://swiperjs.com/, I've been unable to locate an option that allows the slide to return immediately to the right once it goes out of view on the left. The current behavior poses a problem where there is no next slide o ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...