F
F
fandorin_official2017-11-18 17:30:47
JavaScript
fandorin_official, 2017-11-18 17:30:47

How to restart XMLHTTPRequest request?

There is a piece of a script which does XMLHTTPRequest request. From time to time, the server processing the request hangs. And then the script hangs. You have to manually restart.
How can the XMLHTTPRequest request be improved so that if something happens (in the absence of a response from the server) it will restart.
Initially the code is like this:

var xhr = new XMLHttpRequest();
xhr.open('GET', diceLink);
xhr.onreadystatechange = function() {
            if (xhr.readyState == 4){
                r=xhr.responseText;      
            }
 
        };
        xhr.send()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey delphinpro, 2017-11-18
@delphinpro

var timeout;

function send() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', diceLink);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4){
      clearTimeout(timeout);
      r = xhr.responseText;      
    }
  };
  xhr.send();

  // ждем 10 сек... не лучшее решение, но как ещё — хз.
  timeout = setTimeout(function(){
    xhr.abort(); // Останавливаем
    send();      // Запрашиваем снова
  }, 10000);
}

send();

N
Negwereth, 2017-11-19
@Negwereth

https://developer.mozilla.org/en-US/docs/Web/API/X...

D
Dima Pautov, 2017-11-18
@bootd

and some kind of answer should still come, that the server is not responding !! Here, focus on it. If the server does not respond, then re-run the script

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question