Need help on XHR (XMLHttpRequest).

Suppose I send a GET request to /msg.php. From there I receive the data (messages) and through innerHTML I deduce. Requests are sent via setInterval(message, 2000); that is, every 2 sec.

Here's a question, how to implement let's say this:

GET goes to /msg.php, wait 25 sec. is there an answer (or message), and repeat again.

Noticed, this principle works in VK (example)

  • 2
    This is called long polling. Use WebSocket better. - user207618
  • Or chat Iframe 😃 - ishidex2
  • There is no need for ajax - ishidex2

2 answers 2

There is a timeout for this. I understand you need something like this:

 var xhr = new XMLHttpRequest(); xhr.timeout = 25000; // Время в миллисекундах xhr.ontimeout = function (evt) { // Таймаут. Здесь можно выполнить что-нибудь.. }; 

Here you can read on MDN https://developer.mozilla.org/ru/docs/Web/API/XMLHttpRequest/timeout

    You have the answer in the question itself

    GET goes to /msg.php, wait 25 sec.

    If you just simplify the example for clarity, then inside msg.php write:

     $end = time() + 25; while (time() < $end) { // тут проверяем наличие новых сообщений и выполняем для них echo // echo '<script>msg("test!")</script>' sleep(1); } 

    On the client in JS, process the received calls to msg() and restart the whole process with a new one every 30 seconds. (This is historically a connection timeout in good old IE and everyone sticks to it).

    Or just plug in a thread socket.io . Everything is out of the box, cross-browser, but written on node.js.