Tengo el siguiente código que actualiza un archivo PHP cada 9 segundos. Esto funciona bien, pero me gustaría tener un tiempo de espera en caso de que un usuario deje la página abierta. Debería dejar de actualizar la llamada después de 5 minutos; de lo contrario, seguirá cargando mi archivo PHP indefinidamente desperdiciando recursos del servidor. ¿Cuál es la forma más simple y eficiente de hacer esto con jQuery?
Aquí está mi código:
(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);No puedo replicar tu ejemplo. Considere el siguiente ejemplo algo similar.
$(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> Puede usar Date.now() o puede usar new Date() . De cualquier manera, desea capturar la fecha y hora cuando comienza el script y luego clearInterval() cuando haya pasado suficiente tiempo.