At what point are local objects garbage collected?

M

Mike Harrison

Hi, I've got a question regarding garbage collection of image objects
that are assigned to a local variable.

Is it safe to write code like below? This code assigns a new image to
a local variable and sets an onload handler, which gets called after
the variable has gone out of scope.

The handler always seems to get called even though there are no
remaining references to the object, so I wondered at what point the
image gets marked for garbage collection?

Is there a chance it could be deleted before the load handler is
called?

<script type="text/javascript">

function ImageLoaded(e)
{
alert ("Image loaded");
}

function LoadImage()
{
var img = document.createElement ("img");
img.addEventListener ("load", ImageLoaded, false);
img.src = "image.jpg";
}

LoadImage();

</script>
 
T

Thomas 'PointedEars' Lahn

Mike said:
Is it safe to write code like below?
[...]
function ImageLoaded(e)
{
alert ("Image loaded");
}

function LoadImage()
{
var img = document.createElement ("img");
img.addEventListener ("load", ImageLoaded, false);
img.src = "image.jpg";
}

LoadImage();

Very likely, yes. In particular, it is good in that it avoids the problem
of circular references involving DOM objects which would cause memory leaks
in MSHTML.

However, it does not make sense.
This code assigns a new image to a local variable and sets an onload
handler, which gets called after the variable has gone out of scope.

That is why it avoids the problem described above.
The handler always seems to get called even though there are no
remaining references to the object,

There is very likely still a reference to the object in the DOM
implementation's event registry.
so I wondered at what point the image gets marked for garbage collection?

Very likely not before the event listener was called.
Is there a chance it could be deleted before the load handler is
called?

Only a very small one. It does not make sense to garbage-collect an object
that you have just added an event listener for.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top