How to send Ajax request on every 1s using JQuery?

后端 未结 5 1510
独厮守ぢ
独厮守ぢ 2021-01-03 06:43

How to send Ajax request on every 1s using JQuery ?

5条回答
  •  独厮守ぢ
    2021-01-03 07:38

    You probably don't want to send a request every second as David already noted.

    Therefore, using setInterval is a bad idea.

    Instead consider doing something like this:

    function doAjax() {
    
      $.ajax({
       ...
       complete: function() {
        setTimeout(doAjax,1000); //now that the request is complete, do it again in 1 second
       }
       ...
      });
    }
    
    doAjax(); // initial call will start rigth away, every subsequent call will happen 1 second after we get a response
    

提交回复
热议问题