AppleGrew
AppleGrew

Reputation: 9570

When Javascript objects are garbage collected from memory?

I have seen similar threads on this QnA, but my specific scenario is as below.

function render(canvas) {
    var renderer = new Renderer(canvas);
    renderer.render();
}

Renderer.render() draws some stuff on the <canvas>. Now the thing is that this works, so this means instance renderer is not garbage collected. This brings me to my question - when will renderer be garbage collected? Note that this object is referred nowhere else, except by its own methods.

I would like that object to be garbage collected when it finishes rendering. Is there any way to force that?

Upvotes: 0

Views: 147

Answers (3)

Tim Rogers
Tim Rogers

Reputation: 21713

Your timeout in render() holds a reference to a function, which in turn holds a reference to the renderer. Once the timeout has executed, and provided it doesn't set any more timeouts, there is no reference to the function, and there is no reference to the renderer, so it is clear to be garbage collected.

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

The details of garbage collection are not defined by the ECMAScript specification, so implementations are different in different browsers, but usually in JavaScript an object becomes available for garbage collection when there are no remaining references to it.

In the case of your example, it will be when the function in which renderer is declared returns.

Upvotes: 1

mattn
mattn

Reputation: 7723

in v8 way, There is no references of the object, and javascript engine become idle.

Upvotes: 1

Related Questions