Howard
Howard

Reputation: 19815

Memory leak in JavaScript for event handing

Does the following function has memory leak?

var d = document.getElementById("d");
d.onclick = function() {

    // blah...

};

Upvotes: 0

Views: 294

Answers (4)

Praveen Prasad
Praveen Prasad

Reputation: 32117

<div id="parent">
<span id="child">I am a span</span>
</div>

this is okie

    var d = document.getElementById("child");
    d.onclick = function() {

    // blah...    
};

//clearing an event from dom before removing handler from it will result in memory loss

now doing this will start leaking memory

   document.getElementById("parent").innerHTML="";

Upvotes: 2

Dan Beam
Dan Beam

Reputation: 3927

No, there's no memory leak here.

Additionally, you can use array de-referencing if you want to just do it in one line -

document.getElementById("d").onclick = function() {
    // blah...
};

but this is dangerous if the element isn't present (or the DOM's not ready, etc.), as document.getElementById returns null if the object isn't found in the DOM (and though null is an object when you typeof, it's not cool with you trying to set properties on it).

Ah, the quirks of JavaScript.

Upvotes: 1

Kamran Khan
Kamran Khan

Reputation: 9986

No.

All local variables, that is variables declared inside a function(on stack) tends to lose the scope as soon as the method call is complete.

Also, when you are done with the d you can delete it as well; delete d;

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

This is not memory leak. It's attaching onclick handler to a DOM element and is quite common.

Upvotes: 0

Related Questions