如何通过与Jquery中的时间进行比较来创建ajax请求

How to create an ajax request by compare with times in Jquery?

本文关键字:比较 创建 请求 ajax 时间 何通过 Jquery      更新时间:2023-09-26

我想通过使用Ajax请求来请求一个内容,并将当前时间与参数(数据)进行比较,以在getresult函数中检查为IF条件。

我想使用getresult来检查我的参数(数据)是否等于startTimes()函数中的18001300时间。因此,如果我的条件是通过,我将调用ajax并停止。

我的问题当我的getresult满足条件时,我的ajax将请求119次。

有人有更好的功能来构建这个功能吗?请帮助我。

startTimes();
function checkTimes(i) {
    return i;
}
function startTimes() {
    var today = new Date(),
            h = today.getHours(),
            m = today.getMinutes(),
            s = today.getSeconds();
    var t = h + '' + m;
    setTimeout(function () {
        startTimes();
    }, 500);
    getresult(t);
}
function getresult(data) {
    if (data == 1800) {
//        Ajax request here
    }if(data == 1300){
//        Ajax request here
    }
}

它被调用119 (actually is 120)次,因为您每500毫秒调用一次函数,在一分钟之前,时间仍然是1800或1300,具体取决于情况。

因此,更具体地说,120 * 500 = 60000 miliseconds or 1 minute,到那时比较是不同的。你可以将超时时间更改为一分钟检查,试试这个:

//Run every minute
setInterval(function() {
    startTimes();
}, 60000);    //1000 milliseconds * 60 seconds
function startTimes() {
  var date = new Date();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  //call ajax at 18:00
  if(hours == 18 && minutes == 0) {
    //ajax request here
  }
  //call ajax at 13:00
  if(hours == 13 && minutes == 0) {
    //ajax request here
  }
}