Dealing with memory leaks in AngularJS websocket service

Within my project, there exists an angular factory responsible for managing the websocket connection with a c++ application.

The structure of this websocket factory is as follows:

.factory('SocketFactory', function ($rootScope) {
    var factory = {};

    factory.connect = function () {
        if(factory.ws) { return; }

        var ws = new WebSocket('ws://...');

        ws.onopen = function () {
            console.log('Connection to the C++ App established');
        };

        ws.onerror = function () {
            console.log('Failed to establish the connection to the C++ App');
        };

        ws.onclose = function () {
            console.log('Connection to the C++ App closed');
        };

        ws.onmessage = function (message) {
            //perform operations here
        };
        factory.ws = ws;
    };

    factory.send = function (msg) {
        if(!factory.ws){ return; }
        if(factory.ws.readyState === 1) {
            factory.ws.send(JSON.stringify(msg));
        }
    };

    return factory;
});

The c++ application will transmit images via websockets, which will then be displayed in a canvas that updates with each new image received.

Although everything functions correctly, upon sending images to the browser, I noticed an increase in memory usage by the Chrome process in Ubuntu's system resource monitor, fluctuating around +/-5mb each time ws.onMessage is triggered (approximately).

Even after removing the code within ws.onMessage and solely retaining event detection, the memory consumption continues to rise. Should I utilize $destroy to resolve this issue and prevent such memory leaks?

Answer №1

I was surprised by how confusing this situation turned out to be.

Instead of the websocket service indicated in the initial instructions, I ended up using a different one: https://github.com/gdi2290/angular-websocket

Although the memory leak continued, I identified that there was a lingering reference to an imageObj.src during the canvas updating process that needed to be cleaned up properly.

Now, it appears that Chrome, Opera, and Firefox are all maintaining memory usage within acceptable boundaries.

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

Ensure the form is submitted before triggering the AJAX API call

Solution: To solve the issue of PHP variables not being found, you can simply prevent default submission and utilize Javascript variables in your API call. I am currently exploring a workaround to ensure that the form is submitted before making an API cal ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

How can you use JavaScript to swap out a character in various elements sharing the same class?

My webpage contains multiple paragraphs with the same class name. I need to remove a specific character from all of them. My attempt at using jQuery is as follows: var str = $(".foo").html; var res = str.split(" ").join(""); $(".foo").html = res; ...

Styling an element with CSS through JavaScript manipulation

Welcome to my first post here! :) So, I'm currently working on a project for my college where I need to create "task notes" that fade in each time I add one to an array. .note_input { height:255px; width:200px; background-image:url(&apos ...

Using Javascript to search through nested arrays for specific elements

What is the best way to filter an inner array of objects by key value when given an array with objects that contain options? Consider the scenario below: let test = [{ "options": [{ "label": "Audi", "value": 10 }, { "label": "BMW" ...

Ways to mandate adjusting an option in <select> tag

Using the code $('select').change(function(){alert('changed');});, I am able to trigger an alert every time the option is changed. However, I also need to trigger the alert when the default option, which is the first one in the list, is ...

Utilize Google Autofill to easily populate address fields in a form

I've come across several autofill address codes, but I'm looking to integrate a Post function that would allow me to post the obtained data to a PHP page. Is there anyone who can assist with the javascript or HTML code to achieve this? HTML Cod ...

What is the best approach for incorporating style tags into a webpage - dynamically inject them into the head or include them directly in the

My website includes html content that is fetched from another server and embedded into a page during the server-side compilation process. The issue arises when this embedded content contains its own css, leading to unstyled flashes on mobile devices desp ...

What steps should I take to fix the WCF / AJAX problem I'm encountering? (Receiving a 400 Bad Request error

I am relatively new to AJAX and JavaScript, so I appreciate your patience. My goal is to use an AJAX call to send a new user object to a WCF C# method, which will then create the user in a SQL server database. Subsequently, the C# method will send back a v ...

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

Creating a new controller with an isolated scope for testing purposes

I'm encountering an issue with my controller test file. Here are the initial lines: scope = $rootScope.$new(); ctrlInstance = $controller( 'formCtrl', { $scope: scope } ); The problem lies in the instantiation of the controller, as the sco ...

Using a Javascript variable within a regular expression

Looking for guidance on how to effectively use a variable in a regular expression with JavaScript. I attempted this approach: var regex = new RegExp('/^' + name + '/'); var result = cookie.name.match(regex); However, when I debug the ...

Limiting the maximum date for a datepicker

Looking to customize my datepicker code so that maxDate is only applied when selector === '#Birth'. Any suggestions on how to accomplish this? function customdatepicker(selector) { $(selector).datepicker({ inline: true, showO ...

Using Angular-Resource instances throughout the entire application

Within my code, I have set up a straightforward resource of categories that utilizes a cached query action: app.factory 'Category', ($resource) -> $resource "/categories/:id", {id: '@id'}, { query: { cache: true, isArray: true, ...

Having trouble getting routing to function properly with react-router-dom

I'm currently assisting a friend with completing a React Project. I'm facing an issue while trying to set up routing using react-router-dom. The components inside the <switch> tag are not functioning properly. Below are snippets of my code: ...

AngularJS $http.get('') is throwing an error because some parameters are missing

I am currently working on an application that utilizes OAuth for authentication, but I am facing some issues with passing the URL parameters correctly. Despite trying various methods, my API keeps returning an error stating that the username and password a ...

What is the best way to display and conceal various elements with each individual click?

Utilizing the onClick function for each triggering element, I have implemented a show/hide feature for multiple element IDs upon click. The default setting is to hide the show/hide elements using CSS display property, except for the initial 3 main elements ...

PHP Ajax login form to instantly authenticate without redirecting to a new page

After attempting to implement Ajax in my login form by following two different tutorials, I am still facing the issue of error messages redirecting to another page instead of displaying on the same page. I have tried to troubleshoot and compare my code wit ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...