浏览器变为空闲后,保持setTimeout功能运行

时间:2016-02-25 21:42:00

标签: javascript

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

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

$(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();
});

如何在不管浏览器状态的情况下连续运行,或在窗口激活时回调它?

1 个答案:

答案 0 :(得分:1)

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

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);
});