Wednesday, June 5, 2024
183
rated 0 times [  190] [ 7]  / answers: 1 / hits: 7983  / 10 Years ago, tue, february 17, 2015, 12:00:00

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?


More From » garbage-collection

 Answers
6

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;

[#39199] Monday, February 16, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elians

Total Points: 417
Total Questions: 87
Total Answers: 101

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
;