JQuery recursive ajax polling using setTimeout to control polling interval

$(document).ready(function() {
    (function poll() {
        setTimeout(function() {
            $.ajax({
                url: "/project1/api/getAllUsers",
                type: "GET",
                success: function(data) {
                    console.log("polling");
                },
                dataType: "json",
                complete: poll,
                timeout: 5000
            }), 5000
        });
    })();
});​

It just runs as fast as the server can respond, but I was hoping it would poll every 5 seconds. Any suggestions?

EDIT: I have to add, 5 seconds after completing the request.

+5
source share
3 answers

It seems that you managed to get the delay argument setTimeoutwritten in the wrong place.

$(document).ready(function() {
  (function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/project1/api/getAllUsers",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 5000
        }) //, 5000  <-- oops.
    }, 5000); // <-- should be here instead
  })();
});​

If you follow the curly braces, you will see what you call setTimeoutlike:

setTimeout(function () {
    $.ajax(), 5000
})

and should be

setTimeout(function () {
    $.ajax();
}, 5000)

This should trigger AJAX polling 5 seconds after completing the previous one.

+6
source

5 5 , setInterval. , , .

function poll() {

            $.ajax({
                url: "/project1/api/getAllUsers",
                type: "GET",
                success: function(data) {
                    console.log("polling");
                },
                dataType: "json"
        });
    }

setInterval(poll, 5000);
+1

If you want to use jQuery syntax syntax rather than callback syntax, here is another neat way.

function poll() {
    $.get('http://your-api-endpoint.com')
    .done(function() {
        // 200 - OK response
    })
    .fail(function() {
        // Error Response
    })
    .always(function () {
        setTimeout(function() {
            poll();
        }, 5000);
    });
}

poll();
0
source

All Articles