是否可以在JavaScript(Jquery)中获得当前时间加上3秒的setInterval?

是否可以在JavaScript(Jquery)中获得当前时间加上3秒的setInterval?,javascript,Javascript,我不知道如何在setInterval(或javascript中的替代方法)中获得当前时间延迟加上3秒的函数 我的密码在这里 setInterval(function() { $.ajax({ url: "chat_online.php", method: "POST", success: function(data) { $('#online').html(data); } }); }, 30

我不知道如何在setInterval(或javascript中的替代方法)中获得当前时间延迟加上3秒的函数

我的密码在这里

setInterval(function() {
    $.ajax({
        url: "chat_online.php",
        method: "POST",
        success: function(data) {
            $('#online').html(data);
        }
    });
}, 3000); /* here I want current time plus 3 seconds*/

你要求另一种方法。您当前的设置将每三秒运行一次Ajax代码。要在一段时间间隔后严格运行代码一次,请执行以下操作:

setTimeout(function(){console.log("this code runs after 3 seconds");}, 3000);

首先,您必须认为您的代码在做什么? 我的意思是在计时器中调用异步函数,异步函数可能有延迟或等待服务器。。。然后每3秒钟发送一个请求,但没有收到最后一个请求的成功! 因此,除了您的代码外,我提供以下代码:

var online = $('#online');
function getOnline (){
    $.ajax({
        url: "chat_online.php",
        method: "POST",

    }).then(()=>{
        online.html(data);
        setTimeout(getOnline,3000);
    });
};

getOnline();
顶级代码首先发送请求,然后从服务器接收响应

(在这段代码中,成功就是过程。你必须有一个计划 (对于失败请求)


,三秒钟后再次运行。我知道这不是你想要的,但必须考虑异步功能。 您可以通过以下方式获得当前时间的第二个值

var sec = new Date().getUTCSeconds();
var timeOutVariable = sec + 3; // add 3 sec to it

setInterval(function() {
$.ajax({
        url: "chat_online.php",
        method: "POST",
        success: function(data) {
            $('#online').html(data);
        }
    });
}, timeOutVariable * 1000); // our variable here
并不是说
setInterval
的问题在于一旦
setInterval
您就不能更改
setInterval
的时间。在这种情况下,您必须递归地
setTimeout
以获得所需的效果

function timeOut(time) {
  setTimeout(
    function() {
      /* your stuffs here */
      // recalculate sec val and settimeout again
      recursiveTimeoutFunc();
    },
    time
  )
}
// calculate seconds in here
function recursiveTimeoutFunc() {
  var sec = new Date().getUTCSeconds();
  var timeOutVariable = sec + 3; // add 3 sec to it
  timeOut(timeOutVariable * 1000); // call from here
}

什么不适用于您的代码?当前时间是指当前时间的第二个值吗?i、 e如果时间是23:19:
07
您想要
07s+3s=10s
?您的代码已经建立了间隔计时器,这样第一次调用回调将在调用
setInterval()
后3秒。如果您只想调用一次,则使用
setTimeout()
而不是
setInterval()
3000
已经表示当前时间后的3秒。我们需要进一步澄清你到底想做什么。“或其他方法”