The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality after around 30 reloads but also causes unexpected behavior. For example, I recently added rotation to the object rendering function, and with each reload, the rotation button starts spinning faster. After just 5 reloads, it spins out of control. The spinning function in question is quite simple:

    function animate() {
    if (typeof(objektas) !== 'undefined') {
        rotation++;
        if (rotation >= 360) rotation = 0;
        objektas.rotation.y = rotation * Math.PI * 2 / 360;
    }
    requestAnimationFrame(animate, renderer.domElement);
    renderer.render(scene, camera);
}

I suspect that with every reload, these animate functions are stacking up, causing them to be called multiple times instead of once. Can anyone provide insights on how to resolve this issue?

Answer №1

Utilizing recursion, the animate function continuously reinvents itself, creating a perpetual loop.

Each time the function is reloaded, another instance of the animate loop is initiated. This results in multiple intertwining loops on the UI thread, causing the rotation variable to increment at an accelerated rate.

If invoked repeatedly, these interweaving loops can lead to significant performance issues. The key to resolving this is ensuring that the function is only called once from the initial invocation point.

One approach is to introduce a global variable:

var hasCalledAnimate = false;

Subsequently, modify the first invocation as follows:

if(!hasCalledAnimate) {
   hasCalledAnimate = true;
   animate();
}

To prevent any possibility of a second call, utilize closures:

var animate = (function () {
       function _animate() {
           if (typeof(objektas) !== 'undefined') {
               rotation++;
                if (rotation >= 360) rotation = 0;
               objektas.rotation.y = rotation * Math.PI * 2 / 360;
           }
           requestAnimationFrame(_animate, renderer.domElement);
           renderer.render(scene, camera);
       }
       var _hasInvoked = false;
       return function () {
           if (!_hasInvoked) {
               _hasInvoked = true;
               _animate();
           }
       }
   })();

This revised version ensures that animate remains truly idempotent, allowing for multiple calls while guaranteeing the loop is initiated just once.

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

`How can I incorporate personalized animations on Google Map V3 Markers as they are individually dropped on the map?`

This is a basic example of dropping markers one by one on Google Maps V3. I have implemented the drop animation when adding markers to the map. However, I am interested in customizing the drop with a fade animation. Is it possible using JavaScript or any ...

There is an issue as headers cannot be changed after being set for the client

I am in the process of developing an employee leave management system. Everything runs smoothly until an issue arises when attempting to update the leave status as an admin, and the logged-in account or user does not have admin privileges. There is a midd ...

Creating movement in three distinct divisions

I am seeking a way to have three divs flying in upon click. The first DIV is positioned at the top, followed by one on the left and one on the right (both being below the top one). I wish for them to fly in from their respective directions - the top div fr ...

Ways to fix the error message 'yarn package has unresolved peer dependency'

Whenever I run yarn upgrade or install, a bunch of warnings pop up due to unmet peerDependencies. warning " > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4322332c2f2f2c6e2f2a2d286e2b37373303726d766d7a">[email pro ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

I'm having trouble with Material Design Slide Toggle as it lacks event.StopPropagation functionality. Any suggestions on what alternative I

When working with the Slide Toggle in Material Design, I noticed that it does not have a stopPropagation event. This is because the "MdSlideToggle.prototype._onChangeEvent" already includes a call to stopPropagation. So, what should be used instead? <m ...

Interactive Bar chart updates in real-time with Highcharts and AngularJs

With the help of a sample from Highcharts (here), I successfully integrated a bar chart into AngularJs. Below is the HTML code: <!DOCTYPE html> <html ng-lang="en" ng-app="myModule"> <head> <meta charset="ISO-8859-1"> <script sr ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

submit a new entry to add a record to the database

Hey there, I recently started learning PHP and JS and I'm trying to insert a row into a WordPress database table. I need to get the information needed for insertion from another table, but I'm facing an issue with the PHP file as it's not in ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

Unable to make an AJAX call to a Spring controller

I am currently attempting to make an ajax call to a Spring controller, but I am encountering an Error 405 stating "Request method 'POST' not supported." I have included my code below and would appreciate any suggestions on how to resolve this iss ...

Why won't the infowindow close when I press the close button in the markercluster of Google Maps API v3?

initialize map function initializeMap() { var cluster = []; infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map"), { cen ...

Adding local JavaScript to a Vue component is a great way to enhance its functionality

I am currently working on integrating a homepage concept (Home.vue) into my project. The design is based on a template that I purchased, which includes CSS, HTML files, and custom JavaScript. While most of the CSS has been successfully imported, I am havin ...

posting data and redirecting fails when using an ajax button

I am encountering an issue where I click a button on a page to navigate to another page with posted data, but it is redirecting without posting anything. Both $_POST and $_SESSION variables are empty. Below is my ajax function: function ajax4(Div_Submit, ...

Display an input field in VueJS with a default value set

Dealing with a form containing various editable fields, I devised a solution. By incorporating a button, clicking it would conceal the label and button itself, while revealing a text box alongside a save button. The challenge lays in pre-filling the textbo ...

Tips for efficiently exporting and handling data from a customizable table

I recently discovered an editable table feature on https://codepen.io/ashblue/pen/mCtuA While the editable table works perfectly for me, I have encountered a challenge when cloning the table and exporting its data. Below is the code snippet: // JavaScr ...

Out of the blue synchronization issues arising from utilizing the nodejs events module

In my code, I am utilizing the Node Events module to execute a function asynchronously. var events = require('events'); var eventEmitter = new events.EventEmitter(); eventEmitter.on('myEvent', f2); function f1(x, y) { console.log( ...

javascript Incorrectly using location.reload will not refresh the page as intended

My goal is to refresh a page every time a user clicks a button so the page reverts back to its original source code. However, I am facing an issue where the location.reload() function is being executed after the code instead of at the beginning. btn.addEve ...

What is the best way to set the theme for Material-UI in a React application?

I find myself puzzled when it comes to styling a front-end based on Material-UI. Can someone clarify where the theme originates from in the following example code and what impact the theme has? import React from "react"; import Container from "@material- ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...