I have a functionality that submits some parameters via AJAX and displays returned results.
setTimeout(function(){
var request = new XMLHttpRequest();
request.open("POST", "/ajax.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
document.getElementById("lst").innerHTML = this.response;
};
request.send("op=list<="+lat+"&ln="+lon+"&mi=1");
}, 1500);
It works but sometimes no results are found and I need to increase the last parameter "mi" to a higher value and repeat the submission. I decided to create an array and loop through it until I get results.
setTimeout(function(){
var dist= new Array(1,5,10,20,50);
dist.every(v => {
var request = new XMLHttpRequest();
request.open("POST", "/ajax.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
document . getElementById("lst") . innerHTML = this . response;
return false;
};
request . send("op=list<=" + lat + "&ln=" + lon + "&mi="+v);
return true;
}
});
}, 1500);
That’s theory, not sure how to put it all together.
Don’t use
setTimeout
orsetInterval
— those will wait an arbitrary amount of time, which will either be too short (leading to bugs) or too long (leading to poor performance). Instead, wait for each request to finish before starting the next one.This can be achieved fairly easily with the
fetch
API andasync/await
: