javascript - 每分钟第 20 秒进行 AJAX 调用

标签 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);

如有任何帮助,我们将不胜感激。

最佳答案

如果您的意思是仅在第 20 秒,如 13:00:20、13:01:20、13:02:20>,...

你必须做这样的事情:

// 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 
);

代码每秒检查一次(如果是第 20 秒)。对于客户端来说,性能可能有点沉重,需要进行多次调用,但它确实有效。

想想:
可以通过在命中或更高的间隔长度后更改 inertval 来优化它,或者使用 setTimeout 代替,并计算下一次调用它自己的时间。

顺便说一句: 如果您还想获取毫秒,则必须降低间隔并查询 now 变量的 getMilliseconds() 函数,但这会可能会降低客户端的性能。

可选(just4fun):
如果你想减少 setInterval 调用,你可以使用 setTimeout 并递归调用该函数,“问题”是,如何调整时间设置以接近 20 日秒不会错过。

这是一个简单的基本示例,可以从以下位置开始:
(是的,代码不是很优化,并且可以更好地构造,但我希望它给出一个粗略的想法)

// 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);

关于javascript - 每分钟第 20 秒进行 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42342085/

相关文章:

javascript - 任何让输入模式在 Safari 和 IE8 上工作的方法<

javascript - 失去指令的约束力

javascript - 如何循环一个 div 并使用正则表达式添加一个类?

javascript - 取消选择 jquery 选择对象中的项目

javascript - 将 ajax 转换为 Node.js

Javascript:在 For 循环中创建函数

javascript - event.preventDefault() 和重定向 asp mvc/jQuery

javascript - jQuery .append() 不适用于 .js 文件

jquery - 如何将事件绑定(bind)到 AHAH 请求的 HTML 中的链接组

jquery - 同一页面多次Ajax调用: Ajax calls from within an Ajax loaded div