javascript - 太多的递归?

标签 javascript loops recursion

我对这段代码有疑问。该脚本在某处生成“过多的递归循环”。

脚本通过 AJAX 正确加载数据,但它在循环中运行,JavaScript 调试器说?

    <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>

带有 JSON 格式字符串的 AJAX 请求,这是正确的:

{"2203":{"DateGPS":"2017-10-22T21:10:29+02:00","DateReceived":"2017-10-22T21:10:29.917+02:00","经度” :5.90089,"Latitude":51.98514,"Speed":0,"DOP":0,"VehicleNumber":"2203","VehicleType":"Train A" ,"火车号":"1234"}}

有什么想法吗?

最佳答案

您正在 AJAX 调用的成功函数中设置时间间隔。

setTimeout(getCoords, 5000);

一旦调用 AJAX。 5 秒后,“setTimeout”会注册一个事件。所以实际上在 5 秒后再次调用 AJAX 并再次注册函数(getCoords)并继续进行。所以,你需要通过一些满足你程序逻辑的条件来控制这个“setTimeout”事件的注册。

关于javascript - 太多的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878166/

相关文章:

javascript - CSS 图像换行问题 - 取决于浏览器缩放级别

javascript - 在for循环外访问数组

javascript - 如何展平嵌套的 forEach?

php - PHP while 循环中的 SQL SELECT

python try/except/else 递归

javascript - 如何停止setTimeout递归

javascript - 有没有办法用纯 JS 实现 EventTarget?

javascript - document.body.ononline 和 navigator.onLine 之间有什么区别

algorithm - 为什么递归归并排序优于迭代归并排序,即使后者具有辅助空间复杂性?

javascript - 通过搜索查找文本并突出显示出现错误