AJAX Javascript计数器性能问题setInterval

时间:2017-08-17 01:09:37

标签: javascript jquery python ajax flask

我对一个烧瓶端点进行了ajax调用,该端点对谷歌地图API进行REST调用,获取日期作为响应,并将其传递给生成计数器的ajax成功函数。当计数器变为0时,它应该重复调用烧瓶终点并根据返回的信息生成一个新计数器。我有这个工作,但计数器更新太慢,所以我的逻辑肯定存在一些缺陷,我认为这是我对设置间隔函数的使用,但我是Javascript的新手并不确定。我注意到它在实际更新计数器之前还会将api调用循环7-20次,因此计数器只显示在负数中,直到它这样做

function updateRoute() {

$.ajax({
    url: '/_calculateRoute',
    type: 'GET',
    success: function (resp) {
        console.log(resp);
        var countDownDate = new Date(resp).getTime();
        var x = setInterval(function () {
                var now = new Date().getTime();

                var distance = countDownDate - now;

                var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                var seconds = Math.floor((distance % (1000 * 60)) / 1000);

                document.getElementById("timer").innerHTML = days + "d " + hours + "h " +
                    minutes + "m " + seconds + "s ";

                if (distance < 0) {
                    // When the timer runs out have ajax make a request back to the /test route to return the next train time.
                    clearInterval(x); 
                    updateRoute();

                }
            },

            1000);

    }

});
}

然后Flask端点看起来像:

@app.route('/_calculateRoute')
def calculate_route():

try:
    address = Address.query.filter_by(active=True).first()
    print(address.source)
    gmaps = googlemaps.Client(key='APIKEY')
    now = datetime.now()
    directions = gmaps.directions(address.source,
                                  address.destination,
                                  mode="transit",
                                  departure_time=now)

    departure_time = directions[0]['legs'][0]['departure_time']['text']

    # Convert departure_time list into a string datetime
    time = format_time(departure_time)

    return time

except googlemaps.exceptions.TransportError:
    return "Max retries exceeded with url"

我是否错误地使用了setInterval和clearInterval?我该怎么做才能加快通话速度并使其不像它那样循环?我还好奇,如果在这样的实例中,当你有一个外部API调用时,查询api并将细节存储在数据库中,然后再将它传回前端更有意义吗?我为这个冗长的问题道歉。我是一个很新的开发人员,有很多问题:)感谢任何帮助

0 个答案:

没有答案