jQuery基于当前rest第二次每分钟自动刷新

我有一个jQuery自动刷新我的数据。 我每隔60秒/ 1分钟运行一次。

setInterval(function() { //if every 60 seconds based on current time (count the rest of second from current time) then run the AJAX. $.ajax( { url: "chkProfile.php", type: "POST", data: { }, dataType: "JSON", success: function (jsonStr) { } }) },60000); 

现在我想要在任何时候手动刷新我的页面,例如我在12:20:40并且因为我们知道剩下的秒数是20然后运行AJAX。

目前如果我在12:20:40那么它将在12:21:40运行ajax

我想要的是,如果我在12:20:40那么它应该在12:21:00运行ajax

简单方案:

如果第二个是0 ajax必须运行,你可以每秒检查一次。 试试这个:

 setInterval(function() { var second = parseInt((new Date().getTime() / 1000) % 60); if(second === 0) { $.ajax({ url: "chkProfile.php", type: "POST", data:{}, dataType: "JSON", success: function (jsonStr){} }); } },1000); // or less than 1 sec 

优化方案:

首先计算下一分钟的秒数,并每隔60分钟设置一次间隔。

  // define fetch data function var fetchData = function(){ $.ajax({ url: "chkProfile.php", type: "POST", data:{}, dataType: "JSON", success: function (jsonStr){} }); } // begin when dom is ready $(document).ready(function(){ fetchData(); // run fetchData(); here if you want to ajax at first load time // get remain time to next minute var remainTime = 60 - parseInt((new Date().getTime() / 1000) % 60); setTimeout(function(){ fetchData(); // redo every minute setInterval(fetchData, 60000); }, remainTime*1000) }) 

没有ajax示例的代码段:

 // define fetch data function var fetchData = function() { document.write(new Date()) } // begin when dom is ready $(document).ready(function() { fetchData(); // run fetchData(); here if you want to ajax at first load time // get remain time to next minute var remainTime = 60 - parseInt((new Date().getTime() / 1000) % 60); setTimeout(function() { fetchData(); // redo every minute setInterval(fetchData, 60000); }, remainTime * 1000) })