Jack Vonderberg
Jack Vonderberg

Reputation: 67

To much recursion?

I have a problem with this code. The script generate somewhere a 'too much recursing loop'.

The script is correctly loading the data by AJAX, but it runs in a loop says the JavaScript debugger?

    <script>
  function init_map() {
//var myLatLng = new google.maps.LatLng(52.1238433333,5.18094166667);
    var myLatLng = new google.maps.LatLng(0,0);
    var mapOptions = {
      zoom: 14,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

// Marker plaatsen in het midden, daarna wordt hij verplaatst naar juiste plek.
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

var infowindow = new google.maps.InfoWindow({
    content: 'Treinstel: 2203'
});


marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    draggable: false
});

google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
});


  } 
      google.maps.event.addDomListener(window, 'load', init_map);

  function getCoords() {
    $.ajax({
    url: "api.php",
    type: "GET",
    cache: false, 
    data: {
        action : "trainset",
        number : '2203'
    },
    dataType: "text",
    success: function(returnedData) {
        var jsondata = jQuery.parseJSON(returnedData);
          //console.log(returnedData);
          var coords = jsondata.Latitude+','+jsondata.Longitude;
          //console.log('Lat: '+jsondata.Latitude);
          var coordsArray = coords.split(",");
          moveMarkerMap(coordsArray[0], coordsArray[1]);
          setTimeout(getCoords, 5000);
    },
    done: function(data) {
        //setTimeout(getCoords, 5000); // hier werkt hij niet.
    }   
     }); 
}

function moveMarkerMap(lat,lon) {
    var newLatLang = new google.maps.LatLng(lat,lon);
    map.panTo(newLatLang);
    marker.setPosition(newLatLang);
}      


  //setInterval(getCoords, 10000);

$(document).ready(function(){
    getCoords();
}); 
</script>

The AJAX-request with the JSON-formatted string, which is correct:

{"2203":{"DateGPS":"2017-10-22T21:10:29+02:00","DateReceived":"2017-10-22T21:10:29.917+02:00","Longitude" :5.90089,"Latitude":51.98514,"Speed":0,"DOP":0,"VehicleNumber":"2203","VehicleType":"Train A" ,"TrainNumber":"1234"}}

Anyone an idea?

Upvotes: 1

Views: 55

Answers (1)

Amaid Niazi
Amaid Niazi

Reputation: 162

You are setting the time interval in the success function of your AJAX call.

setTimeout(getCoords, 5000);

Once the AJAX is called. An event is registered by the "setTimeout" after a 5 seconds time. So actually after 5 seconds again AJAX is called and again function(getCoords) is registered and this goes on. So, you need to control this "setTimeout" event registration by some condition that satisfies your program logic.

Upvotes: 1

Related Questions