Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

How to stop a while loop when a file is not found that is using XMLHttpRequest()'s?

$
0
0

I want to loop through local files and grab the information from them. map1.txt map2.txt ...

However when a file does not exist the code does not stop. The rawFile.status returns 404 and the console says it is on the rawFile.send(null) line. It just keeps going through the loop never ending and giving the same error.

I want it to stop making requests once the file does not exist.

i = 0;
  while (i != -1) {
    (function(i) {
      var rawFile = new XMLHttpRequest();
      rawFile.open("GET", "../maps/map" + [i] + ".txt", false);
      rawFile.onreadystatechange = function() {
        if (rawFile.status == 404) {
          break; //(or i = -1;)
        }
        if (rawFile.readyState === 4) {
          if (rawFile.status === 200 || rawFile.status == 0) {
           //do stuff
          }
        }
      };
      rawFile.send(null);
    })(i);
    i++;
  }

Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>