Search code examples
javascriptgarbage-collection

How to detect if an object has been garbage collected in Javascript?


I am building a JavaScript game that creates a Level object using var:

function start() {
   var myGameLevel = new Level(2);
}

This Level object has a lot of functionality, primarily adding elements to the DOM and making them interactive. A simplification:

function Level(i) {
    var _difficulty = i;
            
    this.init = function(){
         jQuery("#container").append(...game elements here...);
         jQuery("#button").on('click', function() {...});
    }
}

My question: How can I know if the Level object created in the start function has been garbage collected or not? I aim to use only var variables so that there are no external references. When the DOM is cleared of all game elements, I EXPECT the Level object to be released from memory, but how can I be sure?


Solution

  • Normally in JavaScript garbage collection is non deterministic. You cant know if or when an object is garbage collected. This applies to objects that are strong referenced.

    In ES12 and after, you can use a FinalizationRegistry.

    Finalizers lets you handle when an object is garbage collected, using a JavaScript callback. Still the limitation is that, when the callback will get executed is non deterministic. It may take a min or an hour.

    // object creation
    let abc = new Array(200).fill(true);
    
    const cleanup = new FinalizationRegistry(key => {
      // your code here
    });
    
    // tagging variable abc to finalizer
    cleanup.register(abc, 'werwer');
    
    // abc = null;