Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Make changes instantly PHP or Javascript

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);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda