Hello, I have a server that gives me a random word and when creating a loop it always gives me the same word and I don't know how to make it give me ten different words. Here the code:
var palabra = "";
function Creapalabra() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
palabra = JSON.parse(this.responseText).word;
palabra = palabra.replace(/á/gi, "a");
palabra = palabra.replace(/é/gi, "e");
palabra = palabra.replace(/í/gi, "i");
palabra = palabra.replace(/ó/gi, "o");
palabra = palabra.replace(/ú/gi, "u");
palabra = palabra.replace(/ü/gi, "u");
}
}
xhttp.open("GET", "http://daw.aitordb.com:4000", true);
xhttp.send();
}
function inicio() {
for (var i = 0; i < 10; i++) {
Creapalabra();
document.getElementById("palabra" + i).innerHTML = palabra;
}
}
Try to isolate the result so that the word value is unique for each request using a callback:
The values of the variable
palabra
are probably being overwritten because it is global and since the requests are asynchronous, they are not necessarily executed in order.Hi, the problem you are having is that the requests are asynchronous, one solution is to create a promise and show it when they arrive
Solution
You can recurse when the request completes so you don't overload the server. Something like this would be: