Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda