Javascript memory leak when switching between images (FireFox4)
I have, what I think, is a fairly trivial bit of javascript. If I run this really fast, so that the situation is exacerbated, memory allocation in FireFox 4 keeps increasing. I tried this in chrome and memory seems to remain stable.
Is this a FF4 issue or do I have I constructed my JavaScript poorly?
Note no other JS files are loaded on the page. I am running FF in "safe mode" with all addons disabled. No other tabs are loaded.
<img id="heartbeat" name="heartbeat" src="/web/resources/graph开发者_Go百科ics/greylight.png" />
<script type="text/javascript">
var hasTimedout = 1;
var lastPollTime = new Date();;
var maxDifference = 6000 * 2; //allows us to miss one poll of the data without showing anything bad
function heartbeat()
{
var curTime = new Date();
var diff = curTime.getTime() - lastPollTime.getTime();
if (diff > maxDifference && hasTimedout == 0)
{
document.getElementById('heartbeat').src = '/web/resources/graphics/greylight.png';
hasTimedout = 1;
}
else if (diff < maxDifference && hasTimedout == 1)
{
document.getElementById('heartbeat').src = '/web/resources/graphics/greenlight.png';
hasTimedout = 0;
}
toggle_visibility('heartbeat');
}
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
setInterval("heartbeat()",20);
</script>
Some info on Javascript garbage collection: SO Thread on JS GC
Of particular interest (perhaps):
- Use delete statements. Whenever you create an object using a new statement, pair it with a delete statement. This ensures that all of the memory associated with the object, including its property name, is available for garbage collection. The delete statement is discussed more in “Freeing Objects.”
- Use the var keyword. Any variable created without the var keyword is created at the global scope and is never eligible for garbage collection, presenting the opportunity for a memory leak.
I can only conclude that you should try pairing your object creation using the "new" keyword with delete statements and see if that makes a difference.
Otherwise the code looks fine.
精彩评论