JavaScript is responsible for creating ENORMOUS memory leaks

Unexpectedly, our home PC has been coming to a sudden halt multiple times over the past few days. It takes nearly half an hour for the UI to recover, sometimes requiring a hard reboot. Upon checking Task Manager, I discovered that one specific PID is consuming approximately 96% of the PC's RAM. Through Chrome Task Manager, I identified it as a webpage created by me.

While I have only some knowledge about memory leaks from hearing about them in passing, I strongly believe that my Javascript code may be causing a memory leak. Is there a recommended practice to modify the code and prevent memory leaks? The suspicion lies on my response() function.

Prior to dismissing this inquiry due to duplication or lack of investigation, I refer to another Stack Overflow post which suggests that case "12124561414": could be the root cause; however, verification was inconclusive. Additionally, the loop within this function does not execute, making it uncertain if that's truly responsible, as I am unaware of any built-in JS tools to identify memory leaks.

Is there a way to run continuous loops without triggering memory leaks (if indeed that’s causing the issue)? Or how can resources seemingly unused be freed up? My intention is to have the busy tone play indefinitely until the page refreshes, but crashing the computer seems unjustified.

The complete JS code for the webpage is provided below:

    [JS code here]

This alternative approach appears promising, albeit untested due to concerns about further PC crashes:

[Modified JS code here]

Answer №1

It seems there is some confusion about infinite loops and how they can impact browser performance. In certain cases, entering an infinite loop can cause a browser to hang. For instance, running the following code in your JavaScript console may result in a similar hang scenario:

var number = "12124561414";
while (number == "12124561414") { /* do nothing */ }

The problem lies in the fact that the while loop executes in the same thread as the GUI loop, causing the GUI to freeze until the loop terminates.

A solution to this issue can be found in code examples you have already provided. Consider the following code snippet which plays a tone after a specified time interval, allowing the GUI to update during that period:

function numberDial() {
    if (dialTone) {
        dialTone.pause();
        dialTone.currentTime = 0;
    }
    clearTimeout(timeout);
    timeout = setTimeout(dial, 2000);
}

By using setInterval instead, you can call the function dial every 2 seconds until you stop it with clearInterval. This allows the GUI loop to continue functioning normally while the interval runs.


In response to your queries:

Is there a best practice to modify code to stop memory leaks?

To prevent memory leaks, carefully design your software so that objects are not retained unnecessarily.

Is there any way to run indefinite loops without causing memory leaks?

A helpful explanation from a Rust document addresses this matter...

... It's quite easy to end up with a collection of objects initialized at the start of a program, left unused within an eternal event loop. These objects will persist until the program ends, potentially wasting resources that could have been reclaimed by the OS upon termination.

In essence, whether a loop causes a memory leak depends on what actions occur prior to the loop execution!

Consider the line console.log(number); just before your problematic loop. This action could potentially lead to an unintended reference to number being stored in logs, which might be the only source of leakage identified in your code.

Upon further examination, it appears that this specific case may not actually constitute a memory leak, as number is declared outside the function scope. However, note that console.log has the potential to interfere with garbage collection processes!

Is there a way to release resources that seem to linger indefinitely?

To allow the garbage collector to reclaim these lingering resources, consider logging conditionally to limit the amount of data stored. The references pushed into logs might inadvertently retain other references, such as back to the global object.

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

JQuery scrolling animation not functioning on a specific page

I'm having trouble figuring out why my animation isn't working on just one specific page. Check it out here: As a test, I added a small gray square in the top left corner. When clicked, the script should scroll you down a bit. However, it seems ...

Syntax Error in Node.js for MongoDB: Unexpected token or invalid symbol

I'm having trouble figuring out what's going on. Node v16.4.2, NPM v7.18.1 const mongoose = require("mongoose"); // const dotenv = require('dotenv') require('dotenv').config({path:'variables.env'}); mongoo ...

Updating the error state of a TextField Component in React MaterialUI upon clicking a button

After clicking a 'search' button, I want to validate input fields in my input form. Many solutions suggest validating the input live as it is entered, but I prefer not to do this because some of the validation processes are costly operations, su ...

Subrouter response yields a 404 error code

I have a router file named ping.js located in the http/api directory: var express = require('express'); var router = express.Router(); router.get('/ping', function (req, res) { res.send("You have accessed /api/ping"); }); module. ...

Struggling to populate a fresh JavaScript array with values submitted from a form

I am currently working on a form to collect Family information that will be used for enrolling in a new benefit plan. My goal is to populate an array with the necessary values for each individual to create the benefit record. While researching, I have only ...

Displaying 100,000 sprites with a faint 0.1 opacity, utilizing see-through backgrounds and crisp antialiasing

In my current setup, I have the following key pieces of code: Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, canvas: canvas }); Textures dot: THREE.ImageUtils.loadTexture('./assets/images/dot.png') Material ...

Each page in NextJS has a nearly identical JavaScript bundle size

After using NextJS for a considerable amount of time, I finally decided to take a closer look at the build folder and the console output when the build process is successful. To my surprise, I noticed something peculiar during one of these inspections. In ...

Ways to calculate the total sum of values in an array of objects using MongoDB techniques

i have a document in my MongoDB collection that has the following structure: [ { "_id": { "$oid": "64a5a396ec152ab4f5e1c60c" }, "firstName": "Ram", "lastName": "Shayam ...

Retrieve information about an object's properties by calling methods on the object itself

Let's say we have a json object structured like this; export const initialState = { name: '', acceptable: false, identified: false, variation: false, variationText: () => { return name.toUpperCase() //just an ex ...

Does the syntax for the $.ajax() function appear to be incorrect in this instance?

I am attempting to use .ajax to retrieve the source HTML of a specific URL (in this case, www.wikipedia.org) and insert it into the body of a document. However, the code provided below is not producing the expected outcome. <!DOCTYPE html> < ...

Switching CSS Unicode to JavaScript

I've been using a few emoji unicodes that work great in CSS: content: "\f410" content: "\f2d1" I attempted to display them with JavaScript, but unfortunately, I was unsuccessful. Any suggestions you have would be ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

Change the order in which two divs (or any other object) are stacked

Is there a simple method using only javascript to change the stacking order of two divs? Assume I have the following four div elements: <div id="div1">Div number 1</div> <div id="div2">Div number 2</div> <div id="div3">Div n ...

The output is displaying an Object instead of a numerical value in JSON

When I try running the URL in Chrome, the output I receive is: { "Train_score": { "0": 0.9892473118 }, "Test_score": { "0": 0.9831932773 } } However, when I attempt to use the following code to retrieve the JSON data using Javascript, co ...

Switching Unicode icon when element is clicked

My form has two inputs - one for text input and the other for submitting, like a button. I have added an icon to the submit button and want it to change when clicked. <input class="searchBtn" id="submit" name="submit" type="submit" value="&#xf002"& ...

My data is not appearing with ng-repeat or ng-bind

One issue I am encountering is that my ng-repeat / ng-bind is not displaying the data within $scope.articles, even though I am getting the expected data in the console. To help identify the problem more easily, I have created a code snippet below: var A ...

"Transforming portfolio photos from black & white to vibrant color with the click of a filter button

I'm currently working on creating a portfolio that includes button filters to toggle between black and white images and colored images based on the category selected. While I have successfully implemented the functionality to change the images to bla ...

Use jQuery to submit a form only after confirming its validity using ajax

I've come across an interesting challenge in a form I'm working on. There's one field that requires server-side validation, so I need to capture the submission, send an AJAX request with the field data, check the result, and either allow the ...

Attempting to retrieve the numerical value displayed on my range slider. (using Bootstrap 4 and JavaScript)

var slider = new Slider('#slider1',{ tooltip: 'always' }); //generate a password function passwordGenerator () { // how long is the password going to be? var passwordLength = document.getElementById('slider1').value; ...