Over time, memory usage increases significantly in JS applications that heavily rely on Ajax

I've noticed significant memory leaks in an app I'm currently developing. Despite its lack of complexity, the app requests approximately 40kb of JSON data from the server every 15 seconds. This data is then used to generate a table on the page. As the data is usually new, it's more cost-effective to redraw the table each time. The table has around 30 lines, with about 5 events attached per line. To update the table, I utilize jQuery's .html() method to replace the existing content with the new data. This triggers jQuery's cleanup functions to detach any previous events associated with the elements being replaced. Additionally, I make sure to delete large HTML variables once they are inserted into the DOM using delete my_var.

I have attempted to identify and address circular references and lingering events, but I haven't delved deeply enough into debugging them. If anyone could provide guidance on optimizing performance for such resource-demanding applications, that would be greatly appreciated. Although I recently acquired "High Performance JavaScript" by Nicholas Zakas, I haven't had the chance to fully explore its insights yet.

For context, after running for approximately four hours, the app consumes around 420,000k of memory in Chrome, significantly more in Firefox or IE.

Any advice would be welcome!

Answer №1

My recommendation would be to create a simplified test version of your script that excludes events. Identifying potential DOM/JS circular references can be extremely challenging. By removing certain variables from the equation, you may find it easier to pinpoint the issue.

Answer №2

I can relate to your situation. I once had a code snippet that checked for errors every 10 seconds and displayed the count of errors in real-time, which caused the browser to consume an extraordinary amount of memory (over 1gb) if left running overnight.

To tackle this issue, I adjusted the polling interval to 2 minutes and advised users to close their browsers at the end of the day. A more efficient approach would have been to implement Ajax Push Engine, allowing data to be pushed to the page only when an error occurred, reducing the frequency of data transmission and lowering memory usage significantly.

Answer №3

Have you considered storing data in an object or a different structure? I once encountered a similar issue with a browser extension causing the array to continuously grow in size. It seems like this could be the root cause of your problem, especially when dealing with such a large volume of data retrieval.

Answer №4

It would be beneficial to include a snippet in your code, as it appears that new variables are being created constantly without the old ones going out of scope and thus not being properly garbage collected.

Consider encapsulating more of your JavaScript within constructors and instances of objects. When your JS consists solely of functions and all variables have global scope instead of being properties of instances, it can result in memory consumption issues.

Answer №5

Have you considered creating the table and assigning events just once, then updating the data within the table every 15 seconds?

Answer №6

1) Repeated use of the Jquery Ajax wrapper can result in memory leaks, which is a well-known issue within the programming community. However, it's important to note that your case may not be as severe.

2) While you have taken the initial steps towards optimization by using lightweight json calls and the delete method, the real problem lies in how events are attached and the manipulation of HTML elements.

To clarify: 1) It is possible that you are reattaching the event listener after each html() call. 2) Every time an ajax call is made, the entire table is redrawn, causing memory leaks. To resolve these issues, consider the following steps: 1) Initialize the table with its base content on the server side. 2) Use $(document).ready to attach listeners to the table cells. 3) Make ajax calls to fetch data, parse the response. 4) Update the table with the new data from the parsed array. Please share any progress you've made so far :)

Answer №7

Recently, I encountered a problem that reminded me of this situation. As it turns out, there was a circular reference lurking within my database. Specifically, an inventory item called ABC123 was marked as being replaced by XYZ321, while at the same time XYZ321 was indicated as being replaced by ABC123. It just goes to show that sometimes the source of the issue may not be where you initially expect it.

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

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

Transform Jupiter Tessellation (JT) documents into JSON format for display in THREE.js

Looking for guidance on rendering .JT files in THREE.js. Explored different options but haven't found a solution yet: Checked various loaders in Three.js but couldn't find one for JT files. Please advise if there's something I've ov ...

Using a Component's Variable in Another Component in React Native

Hello there! Thank you so much for offering your help. I have a component called PlayerWidget and would like to utilize its state variable isPlaying value in the AlbumHeader Component. Here is the code for the PlayerWidget: import React, { useContext, use ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

What is the best way to utilize d3.domain for extracting both d3.min and d3.max values from various columns within a JSON dataset?

I have a JSON file that contains data from different years for "male," "female," and "both" categories. I want to set the minimum value in my domain to be the lowest value across all three columns and do the same for the maximum value. Is there a way for ...

Discover the ID or HREF linked to the current date using moment.js

I'm looking to dynamically add an active class to the current day in my web application. An example of how it currently works is shown below: $( document ).ready(function() { $('a[href*="2208"]').addClass('active'); }); My goal ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

AngularJS: excessive number of event listeners in the view leading to extended loading times

Experiencing an issue with the Angular view when loading the view for the second time. Input: The view loads a list of 1500 items All 1500 items are displayed in a table using ng-repeat with a filter No $watch is used in the view Problem description: ...

What is the reason for the lack of an applied CSS selector?

.colored p{ color: red; } article > .colored{ color:powderblue; } .blue{ color: white; } <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initi ...

Magento: Retrieve all new information on cart items from AJAX response

My shopping cart is displaying a popup window with the following details: I am using AJAX calls to update multiple configurable items in the cart, each with custom options simultaneously. However, I am facing an issue where I only receive data for the fi ...

Creating a unique chrome extension that swaps out HTML and JavaScript components

Is there a possibility to create a Chrome extension that eliminates the JavaScript and CSS from a website while it loads, replacing them with new scripts from a separate source? For example, changing 'Old script' to 'new script', or &a ...

Tips for correctly linking an Event Listener to the worldwide 'window' in Angular 6 and higher

Situation Within our Angular 6 application, an iframe is embedded to showcase third-party data. To facilitate secure cross-domain communication, the child iframe sends messages to the parent Angular app using window.postMessage() API. To receive these mes ...

Issue with activating a Django view using Ajax

I would like to activate a view by simply clicking on an HTML button within a template. Here is the code from my template (test.html): <div id="test_count"></div> <input type="button" value="Get number of records in ...

It is essential for each child in a list to be assigned a unique "key" prop to ensure proper rendering, even after the key has been assigned (in Next

Working with Next JS and implementing a sidebar with custom accordions (created as SideAccord.js component). Data is being looped through an array with assigned keys, but still encountering the following error: Warning: Each child in a list should have a u ...

Loop Through Mongoose to Retrieve Multiple Objects

I am currently facing an issue while trying to retrieve multiple objects from MongoDB using mongoose. In my database, I have two primary collections known as user and order. The user collection consists of an array called 'order history', which ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

What causes $(this) to stop functioning post successful execution?

Here are the code snippets I'm currently working with: $(this).removeClass('page larger').addClass('current'); $(this).siblings().removeClass('current').addClass('page larger'); Interestingly, when I try to pl ...

C# monitoring thread for real-time updates on AJAX console

After reading various posts on StackOverflow about multi-threading, I have not found one that addresses my specific question. In my MVC 3 application, I am importing around 5000 records from an XML document into a database. I want to include an AJAX conso ...

What is the process for transmitting images from React Native to native modules?

Challenge I am facing an issue trying to send an array of locally saved images from the JavaScript side (stored in an assets folder) to both iOS and Android native sides. The native code processes the images and returns a new image successfully when using ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...