0

I have the following code that refreshes a PHP file every 9 seconds. This works ok but I would like to have a timeout in case a user leaves the page open. It should stop refreshing the call after 5 minutes otherwise it will keep loading my PHP file undefinitely wasting server resources. What is the most simple and efficient way to do this with jQuery?

Here is my code:

(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);
nibb11
  • 25
  • 6
  • I would suggest getting `new Date()` when it starts and then check if 5 min have passed each time you perform the AJAX call. – Twisty Jan 25 '22 at 21:02

1 Answers1

1

Can't replicate your example. Consider the following somewhat similar example.

$(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>

You can use Date.now() or you can use new Date(). Either way you want to capture the Date Time when the script begins and then clearInterval() when enough time has passes.

Twisty
  • 30,304
  • 2
  • 26
  • 45