我需要每隔5分钟调用一次函数,持续8小时。问题是必须在同一天。例如,如果用户在3月29日晚上11:59登录系统,现在是3月30日上午12:01,则不再调用该函数。
我知道如何在5分钟内调用它并将jquery ajax调用编码。那部分没问题。我的问题是搞清楚日期。有人请帮助我吗?如果需要,我可以提供更多细节。
先谢谢你,
森
抱歉,我忘了密码:
var startDay;
function keepAlive(currDay) {
var today = new Date().getDate();
if (currDay == today) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ alive: 'true' }",
url: "../ses/imsi_ses_edit.aspx/KeepSessionAlive",
dataType: "json",
success: function(data) {
},
error: function(response) {
alert(response.responseText);
}
});
}
}
window.onload = function() {
startDay = new Date().getDate();
keepAlive(startDay); //Make sure the function fires as soon as the page is loaded
setTimeout(keepAlive, 300000); //Then set it to run again after five minutes
}
答案 0 :(得分:6)
var initDate = new Date(); // Or get the user login date from an HTML element (i.e. hidden input)
var interval;
function keepAlive() {
// Do stuff (ajax call)
}
window.onload = function() {
keepAlive();
interval = window.setInterval(function() {
var now = new Date();
if(now.getTime() - initDate.getTime() < 8*60*60*1000 && now.getDate() == initDate.getDate()) {
keepAlive();
}
else {
// Stop the interval
window.clearInterval(interval);
}
}, 5*60*1000);
}
答案 1 :(得分:2)
function keepAlive(currDay) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ alive: 'true' }",
url: "../ses/imsi_ses_edit.aspx/KeepSessionAlive",
dataType: "json",
success: function(data) {
},
error: function(response) {
alert(response.responseText);
}
});
}
window.onload = function() {
var startDay = new Date().getDate();
var startTime = new Date().getTime();
var interval;
keepAlive(startDay); //Make sure the function fires as soon as the page is loaded
interval = setInterval( function () {
if (startDay != new Date().getDate() || startTime < (new Date().getTime() - 1000*60*60*8)) {
clearInterval(interval);
return;
}
keepAlive();
}, 300000); //Then set it to run again after five minutes
}