每分钟20秒进行一次AJAX通话

时间:2017-02-20 10:28:06

标签: javascript jquery ajax

我正在代码中进行AJAX调用。我想要的是在每分钟20秒击中AJAX呼叫。这是我正在制作的AJAX请求。

setInterval(function(){
    $.ajax({
        url: url,
        headers: { 'x-cyclops-ajax': 'yes' },
        method: 'POST',
        dataType: 'json',
        success: function(data) {
            var chart = $('#container').highcharts();
            var keys = Object.keys(data["histData"]);
            $( "#main-div" ).empty();
            for( var i=0; i< keys.length; i++) {
                chart.series[i].setData(data["histData"][keys[i]]["histFailure"], true);
                $('#main-div').append( '<div class="homepage-availability-inner-div"><h1 class="homepage-availability-text"> ' + keys[i] + ': <span class="dashboard-success">' + data["availData"][keys[i]] + ' </span> </h1></div>');
            }
            chart.xAxis[0].setCategories(data["histKeys"]);
            console.log("Data:" + JSON.stringify(data["availData"]));
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("Did not hit the AJAX call");
        }
    });
}, 5000);

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:4)

如果你的意思是仅在第20秒和13:00: 20 ,13:01: 20 ,13:02: 20 ,...

你必须做这样的事情:

&#13;
&#13;
// the interval can be set lower depending on the use case, to be more accurate
// Warning a too low interval setting might kill the performance of the browser/client, 
// and execute the ajax multiple times, if the milliseconds are not considerate 
let interval = 1000;

// the function is called (about) every second, 
// so approximately 60 times per minute and executes the ajax call only once. 
setInterval(
  function(){
    let now = new Date();

    // should only fire, if it is the 20th Second in the current minute
    if(now.getSeconds() === 20){
      //ajax call
      console.info(now);
    }
  }, interval 
);
&#13;
&#13;
&#13;

代码检查每秒,如果它是第20秒。对于客户端来说,性能可能有点沉重,做了很多调用,但它确实有效。

想想:
可以通过更改惯量,在达到或更高的间隔长度后,或者使用setTimeout进行优化,并在下次自行调用时进行计算。

<强>顺便说一句: 如果您还想获得毫秒数,则必须将时间间隔设置得更低,并且还要查询getMilliseconds()变量的now函数,但这可能会破坏客户端的性能。

可选(just4fun):
如果你想减少setInterval次呼叫,可以使用setTimeout并递归调用该函数,&#34;问题&#34;是的,如何调整时间设置以接近20秒而不会错过它。

这是一个小的基本例子,从以下开始:
(是的,代码没有经过优化,可能结构更好,但我希望它能给出一个粗略的想法)

&#13;
&#13;
// the 20th Second, when the ajax call should execute
const selectedSecond = 20;

// can be tweaked to hit closer to 20th Second (ms)
let shortInterval = 400;

// depence on the size less calls are made
let safetyBuffer = 2;

// helper Variable, 60 Seconds
let sixtySeconds =  60;

// timeout value which is set dynamic, first time will execute "immediately"
let currentTimeout = 0;

function timeoutHandler(){
     // gets current Time
     let now = new Date();
     let seconds = now.getSeconds();
     if(seconds === selectedSecond){
        // **** here the ajax call should go ****
        console.info("ajax Called!!");
        // sets the next timeout 58s later, not to miss the 20th Second
        currentTimeout = (sixtySeconds - safetyBuffer) * 1000;
     }else if(seconds > selectedSecond){
        // sets the next timeout to 2s beforethe 20th Second
        currentTimeout = (sixtySeconds - safetyBuffer - seconds + selectedSecond) * 1000;
     } else if(seconds < selectedSecond - safetyBuffer) {
        // sets the next timeout to 2s beforethe 20th Second
        currentTimeout = (selectedSecond - safetyBuffer - seconds) * 1000;
     } else {
        // sets the next timeout to shortInterval(=400ms), 
        // for the last 2s, it will be more often, to not miss the 20th second
        currentTimeout = shortInterval;
     }
     
     // calls the function with the new optimized timeout
     setTimeout(timeoutHandler, currentTimeout);      
}

// initial call
setTimeout(timeoutHandler, currentTimeout);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用setInterval方法进行连续循环,当前秒为20时,您可以进行ajax调用。请参阅代码段:

setInterval(function() {
  if(new Date().getSeconds() === 20) {
     // Your ajax call
  }
}, 1000);