5分钟后停止ajax刷新

Stop ajax refresh after 5 minutes

我有以下代码,每 9 秒刷新一次 PHP 文件。这工作正常,但我想有一个超时,以防用户离开页面打开。它应该在 5 分钟后停止刷新调用,否则它将无限期地加载我的 PHP 文件,浪费服务器资源。使用 jQuery 执行此操作的最简单有效的方法是什么?

这是我的代码:

(function($)
{
    $(document).ready(function()
    {
        $.ajaxSetup(
            {
                cache: false,
                beforeSend: function() {
                    $('#content').show();
                },
                complete: function() {
                    $('#content').show();
                },
                success: function() {
                    $('#content').show();
                }
            });
        const $container = $("#content");
        $container.load("example.php");
        const refreshId = setInterval(function () {
            $container.load('example.php');

        }, 9000);
    });
})(jQuery);

无法复制您的示例。考虑以下有点类似的示例。

$(function() {
  function updateBeat() {
    var b = parseInt($(".beats").text()) + 1;
    $(".beats").html(b);
  }

  function checkNow() {
    console.log(start, Date.now(), Date.now() - start);
    return !(Date.now() - start < (5 * 60 * 1000));
  }

  function showNow() {
    $(".seconds").html(Math.round((Date.now() - start) / 1000));
  }

  function reload(frame, url) {
    $(frame).load(url);
  }

  var start = Date.now();
  var refreshId = setInterval(function() {
    if (checkNow()) {
      console.log("Sleep");
      clearInterval(refreshId);
      return false;
    }
    //reload($("#content"), 'example.php');
    updateBeat();
    showNow();
  }, 9000);
})
label {
  display: inline-block;
  width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show-beats"><label>Beats:</label><span class="beats">0</span></div>
<div class="show-time"><label>Seconds:</label><span class="seconds">0</span></div>

您可以使用 Date.now(),也可以使用 new Date()。无论哪种方式,您都希望在脚本开始时捕获日期时间,然后在经过足够的时间后 clearInterval()