1. Computing & Technology

Memory Leaks

From , former About.com Guide

One thing that JavaScript is supposed to do for you is to clean up behind you with the memory used by your script. This does work most of the time but there are some browsers where in certain circumstances the browser will not clean up for you.

One way in which you can confuse some browsers is where you use a closure to attach some code to an element in the HTML DOM. With some browsers the fact that there is memory being used while that DOM element exists is not properly tracked and therefore that memory isn't released when the DOM element that it is attached to ceases to exist.

Note that this is not a problem in all browsers since most of them do manage to track memory use properly and will manage to release all of the memory the scripts in your web page have used by the time that the page has unloaded.

There will also be many instances where you do not notice that there is a memory leak in your page as in many such cases the memory is in fact used until the page is unloaded and if you are only using that particular browser to test that particular web page then you will not see any impact resulting from the browser not having released all of the memory when your page unloads. Where that sort of situation arises those using that browser will just notice their browser getting slower and slower as more pages gradually use up memory that the browser fails to release properly. For the person using the browser the simple solution if that starts to happen to them is to simply close and restart the browser. When the browser is closed all of the memory the browser is using gets released and so when the browser is reopened you start over again with all the memory available again.

The time where the person actually writing the JavaScript is most likely to notice memory leaks is where they have code that is creating and deleting DOM elements during the processing itself. Only there might you have a situation where you have memory being allocated and not released each time some of the code within your page is run and the page itself will eventually run out of memory if this continues while still on that same page.

In this last instance you must perform the memory clean up yourself within your code so as to eliminate the memory leak. It is also preferable to do so where your script leaks memory even though it will not become obvious until many pages have been viewed by your visitor.

©2012 About.com. All rights reserved.

A part of The New York Times Company.