Javascript 在浏览器空闲后保持setTimeout功能运行

Javascript 在浏览器空闲后保持setTimeout功能运行,javascript,Javascript,以下代码用于跟踪数据库中的更新 问题是它将在一段时间后停止运行(可能是在浏览器空闲时) 如何使其在不考虑浏览器状态的情况下持续运行,或在窗口处于活动状态时将其回调?如果出现错误,它将不会重新启动计时器,因此有两种解决方案: A:添加错误处理程序并放入setTimeout(function(){Update();},30000)编码到处理程序中,因为在发生错误的情况下,没有任何东西会重新启动计时器 缺点:如果响应时间长,30秒后的呼叫不准确 $(function() { function

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

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


如何使其在不考虑浏览器状态的情况下持续运行,或在窗口处于活动状态时将其回调?

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

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:但是您只需要安排一次,并且如果下一次出现,您必须中止上一个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);
});

您可以简化#1解决方案:只在
complete:
分支中写入
setTimeout()
一次。从Jquery开始,在成功或错误的情况下,Jquery也会调用complete 1.5 complete。我不知道您的意思是什么:对我来说,仅仅因为
complete:
在任何情况下都会发生,所以它是放置唯一
setTimeout()的正确位置
语句。有两种情况:错误或成功。若在完整的回调函数中编写一次setTimeout代码,那个就太好了。
$(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);
});