0

I'm trying to use AJAX to change the content of a div of the page every 5 seconds. I've realised that it creates a loop that sends more requests every time. It changes the page content but spams requests.

I don't know how to fix it without breaking it even more.

$(document).ready(function() {
  sendRequest();

  function sendRequest() {
    $.ajax({
      url: "chat.txt",
      success: function(data) {
        $('.chat').html(data);
      },
      complete: function() {
        setInterval(sendRequest, 5000);
      }
    });
  };
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
ShyMike
  • 5
  • 4
  • For every iteration of your loop you're creating *another* interval, which means N+1 requests will be sent. As you're recursively calling `sendRequest`, use `setTimeout()`, not `setInterval()` – Rory McCrossan May 04 '23 at 09:00
  • See [this specific answer](https://stackoverflow.com/a/7749109/519413) in the duplicate I've marked – Rory McCrossan May 04 '23 at 09:01

0 Answers0