0

I have a chat system but I want both the notifications and the messages to be updated immediately, I am using this code (setInterval) but it makes requests every 500 seconds so I think it is not very efficient, is there another way to do it?

setInterval(() => {
let xhr = new XMLHttpRequest();
  xhr.open("POST", "INCLUDES/funciones/get-chat.php", true);
  xhr.onload = () => {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        let data = xhr.response;
        chatBox.innerHTML = data;
        if (!chatBox.classList.contains("active")) {

        }

      }
    }
  }

  let formData = new FormData(form);
  xhr.send(formData);
}, 500);
jarlh
  • 42,561
  • 8
  • 45
  • 63
  • This may help: https://stackoverflow.com/questions/4642598/short-polling-vs-long-polling-for-real-time-web-applications – IncredibleHat Feb 28 '22 at 18:02
  • 5
    You want websockets or SSE. No modern web app should be doing this sort of polling. – Alex Howansky Feb 28 '22 at 18:09
  • Yes, I agree with that but what would be the other alternative? – Michael Robles Feb 28 '22 at 18:34
  • 1
    Websockets and server-sent events _are_ the alternatives. Ajax polling (as you're doing now) will always be inefficient and not very real-time. There aren't any other techniques within a web app context which can deliver what you are asking for – ADyson Feb 28 '22 at 18:45
  • @AlexHowansky Adyson Thank you very much so I will investigate more about websockets to implement it in the project. – Michael Robles Feb 28 '22 at 19:22

1 Answers1

1

You should check WebSockets. You can lower the time between requests lowering the second parameter of setInterval but that would be bad. It would be a huge stress for your server that see a spike in the number of requests.

WebSocket, as the name said, open a socket, a permanent comunication channel between the server and client. This allows the server to send messages to the client.

The advantage is that if no message is ready for the client no traffic is sent and no new requests are made from the client to the server.

This is not the right place for a full chat code example because it's quite long. You can see Socket.io not the fastest but maybe the easiest library to work with WebScokets. Here you can find an example of a working chat (server and client) using Socket.IO

wezzy
  • 5,897
  • 3
  • 31
  • 42
  • This is more of a comment rather than an answer. Consider adding more context and a possible example websocket setup or perhaps move this to a comment on the question itself. – War10ck Feb 28 '22 at 18:21
  • Yes, I agree with that but what would be the other alternative? – Michael Robles Feb 28 '22 at 18:35