jQuery根据第二次当前休息时间每分钟自动刷新 [英] jQuery auto refresh every minute based on current rest second time
问题描述
我有一个jQuery Auto Refresh我的数据.我每60秒/1分钟运行一次.
I have an jQuery Auto Refresh my data. I'm running it every 60 seconds/1 minute.
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.
And now I want when anytime I refresh my page manually, Example I'm on 12:20:40 and as We know the rest of seconds is 20 then run the AJAX.
当前如果我在12:20:40,那么它将在12:21:40运行ajax
The current If I'm on 12:20:40 then it will run the ajax on 12:21:40
我想要的是,如果我在12:20:40,那么它应该在12:21:00运行ajax
What I want is, If I'm on 12:20:40 then it should run the ajax on 12:21:00
推荐答案
简单的解决方案:
如果必须运行0
ajax,则可以每秒检查一次.
试试这个:
You could check it every second if second was 0
ajax must run.
Try this:
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分钟设置一次间隔.
first calculate how seconds is remained to next minutes and set interval every 60 minutes.
// 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示例的代码段:
Snippet for none ajax example:
// 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)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于jQuery根据第二次当前休息时间每分钟自动刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!