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

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

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

相关标签:
5条回答
  • 2021-01-03 07:21
    setInterval(myAjaxCall, 1000);
    

    Obviously in the function myAjaxCall() you will do all you ajax stuffs with jquery.

    0 讨论(0)
  • 2021-01-03 07:24

    if you use setInterval method, you may crush the browser, because setInterval is not waiting for ajax function to complete, if server is running slow or user's connection speed is low this may be cause running multiple ajax requests at the same tme

    0 讨论(0)
  • 2021-01-03 07:30

    you can use setInterval, but setInterval ist not part of jQuery:

    setInterval(function() {
        $.get(...);
    }, 1000);
    
    0 讨论(0)
  • 2021-01-03 07:30

    The interval 1 sec is small enough and it can be that you will start the second request before you receive response to the first request. So you should either start the next request after receiving of the previous one (see the suggestion of Martin Jespersen) or save jqXHR from the previous $.ajax request in a variable and use it to abort the previous request (see here an example)

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