What causes the game code to persist instead of being cleaned up by garbage collection?

After the window.onload event fires, I have this interesting code snippet that creates an anonymous game instance.

I find it surprising that the game actually runs at all considering that this entire function is anonymous and doesn't save a reference to the game object anywhere!

What prevents myGame from being disposed of after window.onload? While I understand that Garbage Collection doesn't happen immediately, it's puzzling why the myGame instance doesn't suddenly disappear at some random moment. Could there be something in the Game class code that prevents it from being garbage collected, maybe references to the DOM elements?

Game.js

(function(window){
    window.onload = function() { 
        // create a game instance but don't save the reference anywhere
        var myGame = new Game();
    };

    function Game() {

        var myCar;
        this.name = "Main App";

        this.init = function(){
            this.logMessage("creating a game instance");
        }

        this.logMessage = function(msg) {
            document.getElementById("message").innerHTML += msg + "</br>";
        }

        this.init();
    }
})(window);  

Answer №1

What is the reason behind Game code continuously running and not being garbage collected?

The misconception lies in the fact that even though the message appears to still be displayed, it doesn't mean that your game instance is actively using memory or executing its code. Once the message is set, the Game instance becomes eligible for garbage collection.

In reality, nothing within the code prevents the Game instance from being garbage collected. Sometimes, garbage collection may not occur unless certain conditions like memory pressure necessitate it. Modern engines such as V8 can optimize memory usage effectively without needing immediate garbage collection (for example, by allocating instances on the stack and then deallocating them once they are no longer needed).

Could references to the DOM influence the garbage collection process?

No, references from the game instance to the DOM elements do not hinder garbage collection of the game instance itself. The direction of the reference matters, and simply having references to the DOM elements from the game instance won't prevent garbage collection. Additionally, most retrieved references are not retained beyond their initial use.

Which type of code inside the Game class could halt the garbage collection of the instance?

Any code that establishes a direct or indirect reference to the game instance can impede garbage collection. For instance, modifying the instantiation of Game like:

window.myGame = new Game();

would create a property in the window object directly pointing to the game instance, thus preventing garbage collection. Similarly, adding code like the following within init can also obstruct garbage collection:

var self = this;
document.getElementById("message").addEventListener("click", function() {
    this.innerHTML = self.name;
}, false);

This code creates multiple layers of references starting from the DOM element, through the event handler function, up to the context where Game instance resides.


It's important to note that while the Game function itself remains accessible due to the closure assigned to window.onload, the specific Game instance created temporarily under myGame is eventually removed during garbage collection.

When inspecting Chrome's heap snapshot, instances of Game (the function) can be found but not Game instances (objects) unless deliberately retained.


For reference, after analyzing your code in Chrome's heap snapshot feature, instances of Game were not detected initially. However, retaining the instance explicitly by assigning it to `window.myGame` confirmed its presence in the heap snapshot indicating potential hindrance to garbage collection.

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

I possess a variety of poppers and desire for the opened one to close when another one is opened

Having built a component that generates 6 unique experiences, each with its own popper containing images, I am struggling to figure out how to modify my code so that one popper closes when another is clicked. Here is the current setup: This is the compone ...

Dismiss modal dialog automatically in Bootstrap and navigate to another page upon submission programmatically

Whenever a user visits a page that prompts them to register, I aim to present a Bootstrap modal dialogue asking for their ID and password. Upon clicking the submit button, my objectives are: To verify the password and complete sign-up To close the dialog ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

The Importance and Purpose of Incorporating a Callback

Understanding asynchronous operations and callbacks has been a challenge for me. To improve my familiarity with these concepts, I've been studying code examples that utilize them. However, there's one aspect of this specific code snippet that con ...

Is there a way to view 2D flat items in 3D using either babylonjs or threejs?

I am currently utilizing fabricJS and have created a variety of random drawings (such as circles, squares, and polygon shapes) on a canvas shaped like a rectangle object (Base). My goal is to display all these drawings engraved on the main rectangle objec ...

Issues with Angular routing when using anchor links

Recently, I delved into the world of Angular and encountered an issue with routing not working correctly when using anchor tags. Here's the snippet of code causing trouble: (function(){ 'use strict'; angular.module("PHC",["ngRoute"] ...

Tips on extracting a base64 image from a canvas

I have successfully developed a function that is capable of reading an uploaded image and extracting imageData from the canvas. However, I am encountering difficulty in obtaining the base64 image from that imagedata. Here is my code snippet: function han ...

What is the process for creating URL query parameters?

What is the process for generating parameters after node?_=xxxxxx? If I am using a Python script to access the URL, how can I retrieve these parameters? edit: I apologize for not providing enough information. This is my first post as a novice. I am atte ...

Updating a component when a prop changes

Embarking on my journey into the world of React, I find myself in need of assistance. The issue at hand involves re-rendering data within my Table component. Whenever a new API call is made to create an entry in my database using Prisma, the newly added d ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Ways to conceal a form post-submission

Looking for help with a programming issue - I'm trying to hide a form after submitting form data to prevent multiple submissions. The forms are created dynamically and I've tried hiding both the form and the div it's inside without success. ...

What is the most efficient method for appending /.json to the conclusion of express routes?

I am currently transitioning a DJANGO API to Node.js and have been tasked with ensuring that routes support the .json extension at the end. For instance, sending a GET request to /users/:id/.json should return a JSON object representing the user. The cha ...

Sending all form input data to Ajax for GET request

Today, my goal is to iterate through each textbox with an ID of setting_value, set its name and value to a key-value array, and then send that data in an Ajax request. The problem I'm facing is that it only seems to be inspecting the first instance o ...

Exploring the extraction of elements from list items using jQuery

Can you help me with removing the anchor tag from the list item? This is the current markup: <ul class="yith-wcan-list yith-wcan "> <li><a href="#">Item 1</a> <small class="count">8</small> <div class="c ...

Modify the bg class when the checkbox is selected

Currently revamping my portfolio website and could use a hand with some jQuery code. Hoping to make a parent class react to a checkbox within it. Specifically looking to change the background color to #000 when the checkbox is checked. Struggling to figur ...

Generate an array of JavaScript objects by converting a batch of JSON objects into objects within a Node.js environment

I am working with a prototype class: function customClass(){ this.a=77; } customClass.prototype.getValue = function(){ console.log(this.a); } and I also have an array of JSON objects: var data=[{a:21},{a:22},{a:23}]; Is there a way to cre ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

Erase every picture contained within the element

<div id="uniqueidhere"> <span> <span><img src="image1link"></img></span> <span><img src="image2link"></img></span> <span><img src="image3link"></img></span> <span>&l ...

Is there a way to automatically display the detailsPanel in Material-table upon loading?

I am currently working on creating a subtable for the main React Material-Table. So far, everything is functioning correctly as expected, with the details panel (subtable) appearing when the toggle icon is pressed. Is there a way to have it displayed by d ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...