Ajax Heartbeat using setInterval, Preventing multiple calls at the same time

后端 未结 3 1384
不知归路
不知归路 2021-01-01 00:06

I wish to make an AJAX call using jQuery as a \"heartbeat\" in the background so that my web application can check for new data. For example every 10 seconds.

I hav

相关标签:
3条回答
  • 2021-01-01 00:33

    Instead of using setInterval, call setTimeout() in the AJAX completion callback to start each call 10 seconds after the previous one finishes.

    0 讨论(0)
  • 2021-01-01 00:43

    instead of using setInterval, calculate the request time (usually using a unix timestamp in seconds), how much for 10 seconds, in the server side, use setTimeout the remaining time, so it will vary from user to user, on their ping time (or the business of the site)

    function heartbeat(){
      $.ajax({
        'url': '/where/',
        'success': function(data){
           setTimeout(heartbeat, parseInt(data) * 1000);
        }
      });
    }
    heartbeat(); // initialize it
    

    in the server side, (like in PHP), you would do

    <?php
    // do your stuff
    echo (time() - (int)$time_requested) + 10; // it will vary per user, so if it takes 2 second, it will be 12, if it returns imediately, returns 10 
    
    0 讨论(0)
  • 2021-01-01 00:51

    try setting another timeout from your ajax success function:

    function poll() {
        setTimeout( function() {
            $.ajax(.......).success( function(data) {
                poll();  //call your function again after successfully calling the first time.
            });
        }, 10000);
    }
    
    0 讨论(0)
提交回复
热议问题