gpt4 book ai didi

javascript - 浏览器空闲后保持 setTimeout 函数运行

转载 作者:行者123 更新时间:2023-11-27 23:18:09 25 4
gpt4 key购买 nike

以下代码用于跟踪数据库的更新。

问题是它会在一段时间后停止运行(可能是当浏览器空闲时)。

$(function() {
function Update() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());

// Call Update again after 30 seconds.
setTimeout(function() { Update(); }, 30000);
}
});
}

// Call postData the first time to start it off.
Update();
});

如何让它持续运行,无论浏览器状态如何,或者在窗口变为事件状态时回调它?

最佳答案

如果出现错误,它不会重新启动计时器,因此有两种解决方案:

A.:添加错误处理程序并将 setTimeout(function() { Update(); }, 30000); 代码放入处理程序中,因为在发生错误时不会重新启动计时器。

缺点:如果响应时间较长,30秒后调用不准确

$(function() {
function Update() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());

// Call Update again after 30 seconds.
setTimeout(function() { Update(); }, 30000);
},
error: function() {
setTimeout(function() { Update(); }, 30000);
}
});
}

// Call postData the first time to start it off.
Update();
});

B.:使用setInterval而不是setTimer:但你必须只安排一次,并且如果下一个tick即将到来,你必须中止上一个ajax调用:

$(function() {
var xhr = null;
function Update() {
var postData = "";
if(xhr!=null) { xhr.abort(); } // avoid paralell call of ajax_api.php, so we stop the previous one
xhr = $.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
}
});
}
// Call postData the first time to start it off.
Update();
setInterval(function() { Update(); }, 30000);
});

关于javascript - 浏览器空闲后保持 setTimeout 函数运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com