XMLHttpRequest leak

Below is the javascript code snippet. It doesn't work as expected, please help me on this.

<script type="text/javascript">

   function getCurrentLocation() {
     console.log("inside location");
     navigator.geolocation.getCurrentPosition(function(position) {
       insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude)); 
       });
   }

   function insert_coord(loc) {
     var request = new XMLHttpRequest();
     request.open("POST","start.php",true);
     request.onreadystatechange = function() {
                                     callback(request);
                                  };
     request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng()));

     return request;
   }

   function callback(req) {
     console.log("inside callback");
     if(req.readyState == 4)
       if(req.status == 200) {
         document.getElementById("scratch").innerHTML = "callback success";
         //window.setTimeout("getCurrentLocation()",5000);
         setTimeout(getCurrentLocation,5000);
       }
   }

getCurrentLocation(); //called on body load
</script>

      

What I am trying to achieve is to send my current location to the php page every 5 seconds or so. I can see multiple coordinates in my database, but after a while it gets weird. Firebug is showing very strange logs like simultaneous POST at irregular intervals.

Here is a screenshot of firebug: firebug screenshot

Is there a leak in the program. please help.

EDIT: The expected output in the firebug console should look like this: -

internal location
POST ....
inside callback

/ * 5 seconds later * /

internal location
POST ... inside callback

/ * repeat * /

+2


a source to share


1 answer


Probably not a problem, but I can suggest two refactorings:

Combine the two conditions in the callback ():

if ((req.readyState == 4) && (req.status == 200)) {

      

And you can shorten the setTimeout line to:



setTimeout(getCurrentLocation, 5000);

      

And to fix the problem, can I get you to remove setTimeout () from callback () and replace the getCurrentLocation () call with it? So you only write "callback success" when the callback is triggered, nothing else.

setTimeout(getCurrentLocation, 5000); //called on body load

      

0


a source







All Articles