How to break out of AJAX polling done using setTimeout

淺唱寂寞╮ 提交于 2019-12-08 10:04:32

问题


I want to implement AJAX polling mentioned in this answer. Now I want to break out of polling when server return particular data value. How to do that?


回答1:


Try something like this (where you change the condition to set continuePolling false to whatever you need):

(function poll() {
var continuePolling = true;
    setTimeout(function() {
        $.ajax({
            url: "/server/api/function",
            type: "GET",
            success: function(data) {
                console.log("polling");
                if (data.length == 0)
                {
                    continuePolling = false;
                }
            },
            dataType: "json",
            complete: function() { if (continuePolling) { poll(); }),
            timeout: 2000
        })
    }, 5000);
})();


来源:https://stackoverflow.com/questions/42231496/how-to-break-out-of-ajax-polling-done-using-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!