Im having trouble with my javascript application leaking memory. I've looked up things online and I seem to have closed out any memory alocation in the setInterval loop by using the
variableX = null
technique. But the application is still leaking memory somehow, can anyone point out what might be causing this leak? Here is my code :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(43.46949, -80.54661);
var lat = 0;
var long = 0;
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
function loadXMLDoc() {
var xhr;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else { // code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "coordinates.txt", true);
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
var textfileString = this.responseText;
var longLatString = textfileString.split(',');
lat = parseFloat(longLatString[0])
long = parseFloat(longLatString[1])
textfileString = null
longLatString = null
}
}
xhr.send();
xhr = null
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
setInterval(function () {
loadXMLDoc()
var newLatLng = new google.maps.LatLng(lat, long);
marker.setPosition(newLatLng);
newLatLng = null
}, 16);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
1 Answer 1
You're sending a new XMLHttpRequest without waiting for the old one to complete. If the response takes longer than 16 milliseconds to be received (which it probably will), the "request queue" will grow, causing a memory leak.
Sending requests nonstop is a bad idea. If you need a constant stream of coordinates, pack multiple coordinates into one response and send a new request only when your previous one has completed:
function getCoordinates() {
...
xhr.onreadystatechange = function() {
...
setTimeout(getCoordinates, 30000);
}
}
Better yet, use Websockets.
3 Comments
setTimeout should be behind the readystate==4 condition. You do imply it in your first sentence though.
latandlongare not going to be received yet from theXHRrequest when thevar newLatLng = new google.maps...runs