Long polling issue
Briefly

Long polling issue
"For a game I use long polling to check if it's the player's turn to play. It works fine. But sometimes, if I quit the page using that long polling to go to any other page it happen that the whole thing freezes. Before I was using short polling and never had this problem. There is something I miss somewhere in the long polling...."
"Javascript: function checkTurn() { if (polling === false) { return; } request = $.ajax({ type: "GET", url: "battleship-checkTurn.php", data: { denBrukeren: denBrukeren, id: gameId, }, async: true, cache: false, timeout: 20000, success: function(data) { if (polling === true) { if (data === denBrukeren) { polling = false; loadGame(); } } }, error: function(XMLHttpRequest, textStatus, errorThrown) { console.log('Reached timeout'); }, }); } $(document).ready(function() { setInterval(function() { checkTurn(); }, 20600); }); function abortRequest() { if (request) { request.abort(); } }"
"PHP: <?php require_once '../includes/db-inc.php'; $gameId = $_GET['id']; $denBrukeren = $_GET['denBrukeren']; $exitLoop = false; $returnValue = 'No set value'; while ($exitLoop === false) { $sql = "select * from battleship WHERE id = '$gameId';"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($result); $turnPlay = $row['turn']; if ($turnPlay === $denBrukeren) { $returnValue = $turnPlay; break; } sleep(1); } echo $returnValue;"
Long polling implementation repeatedly issues AJAX requests and uses a PHP while loop that sleeps(1) until the turn condition is met, with no server-side timeout or loop exit condition. The JavaScript starts a new long-poll request on an interval and provides an abortRequest function that is never invoked on page unload, allowing requests to remain active when navigating away. The mismatch between the AJAX timeout, setInterval timing, and a blocking PHP loop can leave connections hanging and produce freezes. Proper cleanup requires aborting pending requests and clearing intervals on unload, and adding server-side connection or execution time limits or client-disconnect checks.
[
|
]