Call jQuery Ajax Request Each X Minutes

2019-01-03 23:52发布

How can I call an Ajax Request in a specific time Period? Should I use Timer Plugin or does jQuery have a plugin for this?

7条回答
男人必须洒脱
2楼-- · 2019-01-04 00:26

A bit late but I used jQuery ajax method. But I did not want to send a request every second if I haven't got the response back from the last request, so I did this.

function request(){
            if(response == true){
                // This makes it unable to send a new request 
                // unless you get response from last request
                response = false;
                var req = $.ajax({
                    type:"post",
                    url:"request-handler.php",
                    data:{data:"Hello World"}
                });

                req.done(function(){
                    console.log("Request successful!");

                    // This makes it able to send new request on the next interval
                    response = true;
                });
            }

            setTimeout(request(),1000);
        }

        request();
查看更多
▲ chillily
3楼-- · 2019-01-04 00:26

You have a couple options, you could setTimeout() or setInterval(). Here's a great article that elaborates on how to use them.

The magic is that they're built in to JavaScript, you can use them with any library.

查看更多
你好瞎i
4楼-- · 2019-01-04 00:28

use jquery Every time Plugin .using this you can do ajax call for "X" time period

$("#select").everyTime(1000,function(i) {
//ajax call
}

you can also use setInterval

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-04 00:32

You can use the built-in javascript setInterval.

var ajax_call = function() {
  //your jQuery ajax code
};

var interval = 1000 * 60 * X; // where X is your every X minutes

setInterval(ajax_call, interval);

or if you are the more terse type ...

setInterval(function() {
  //your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes
查看更多
Deceive 欺骗
6楼-- · 2019-01-04 00:32

you can use setInterval() in javascript

<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>
查看更多
Luminary・发光体
7楼-- · 2019-01-04 00:35

I found a very good jquery plugin that can ease your life with this type of operation. You can checkout https://github.com/ocombe/jQuery-keepAlive.

$.fn.keepAlive({url: 'your-route/filename', timer: 'time'},       function(response) {
        console.log(response);
      });//
查看更多
登录 后发表回答