/    Sign up×
Community /Pin to ProfileBookmark

Possible memory leak using closure

Hello guys…my turn to ask a question. Will the following code leak memory?

[CODE]someElement.onmousedown =
function(e) {
var tmp = this;
var tmpFnc = function(e){tmp.removeEventListener(“mouseup”,arguments.callee,false);};
this.addEventListener(“mouseup”,tmpFnc,false);
};[/CODE]

someElement is pressed causing an eventlistener to be attached for when the element is depressed. When the element is depressed the closure will remove the eventlistener for the mouseup event.

Second question. Is the above identical to

[CODE]someElement.onmousedown =
function(e) {
var tmp = this;
this.addEventListener(“mouseup”,function(e){tmp.removeEventListener(“mouseup”,arguments.callee,false);},false);
};[/CODE]

Does it make a difference whether a reference to a closure is stored in a variable or not?

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@KravvitzSep 07.2007 — As far I know, only IE gets memory links when you do things like that.

[url=http://simon.incutio.com/slides/2006/etech/javascript/js-reintroduction-notes.html#memoryleaks]Check this out.[/url]
Copy linkTweet thisAlerts:
@DokauthorSep 07.2007 — Where is the memory leak?
Copy linkTweet thisAlerts:
@KravvitzSep 08.2007 — I can't explain it any better than the page I linked to. The leak is caused in IE when you save a reference to an element in a function, e.g. an event handler.
Copy linkTweet thisAlerts:
@DokauthorSep 08.2007 — I didn't see your link untill now ?
Copy linkTweet thisAlerts:
@DokauthorSep 08.2007 — The article you link to seems incorrect. Instead I found these two articles which explains the situation in detail:

http://www.codeproject.com/jscript/LeakPatterns.asp

http://msdn2.microsoft.com/en-us/library/Bb250448.aspx
×

Success!

Help @Dok spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...