jQuery recursive ajax poll using setTimeout to control the poll interval

后端 未结 3 1842
梦谈多话
梦谈多话 2021-01-13 03:49
$(document).ready(function() {
    (function poll() {
        setTimeout(function() {
            $.ajax({
                url: \"/project1/api/getAllUsers\",
               


        
相关标签:
3条回答
  • 2021-01-13 04:06

    Incase you wanted to use jQuery's promise syntax, rather than callback syntax here's another tidy 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 讨论(0)
  • 2021-01-13 04:24

    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.

    0 讨论(0)
  • 2021-01-13 04:29

    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);
    
    0 讨论(0)
提交回复
热议问题