user41451
user41451

Reputation: 269

How to break out of AJAX polling done using setTimeout

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?

Upvotes: 0

Views: 818

Answers (1)

Josh Wright
Josh Wright

Reputation: 118

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);
})();

Upvotes: 1

Related Questions