Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery recursive ajax poll using setTimeout to control the poll 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
        });
    })();
});​

This just keeps executing as fast as the server can respond but I was hoping it would only poll every 5 seconds. Any suggestions?

EDIT: I should add, 5 seconds after the request has completed would be preferable.

like image 498
chrisjleu Avatar asked Jun 27 '12 10:06

chrisjleu


2 Answers

It seems that you've managed to get your setTimeout delay argument written 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 braces, you'll see that you're calling setTimeout like:

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

and should be

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

This should call the AJAX poll 5 seconds after the previous one has completed.

like image 153
Richard Neil Ilagan Avatar answered Sep 20 '22 22:09

Richard Neil Ilagan


If it should poll every 5 seconds and not necessarily 5 seconds after completing the last request, you could use setInterval. Don't know if that's acceptable, but it would make recursion unnecessary.

function poll() {

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

setInterval(poll, 5000);
like image 42
Me.Name Avatar answered Sep 22 '22 22:09

Me.Name