I just started in the world of Javascript and I have doubts ...
I have the following function, I want it to repeat as long as the random value is 204. When the code is 200 it must stop, if it is 500 notify error and stop too. The request will be repeated every second (hence the use of setInterval although I do not know if I am doing them correctly)
I also want to try X times and also stop ... I do not know how to implement it, could it be with an accountant?
var myArray = [200, 500, 404, 204];
var encontrado = false;
var cont = 0;
var repeticion = setInterval(function aleatorio() {
var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (rand == 200) {
console.log("HTTP 200! Encontrado!");
encontrado = true;
} else if (rand == 500) {
console.log("HTTP 500! Error interno del servidor");
encontrado = true;
} else if (rand == 204) {
console.log("HTTP 204!");
} else if (rand == 404) {
console.log("HTTP 404!");
}
cont++;
if (encontrado === true) {
stopFunction();
}
}, 1000);
function stopFunction() {
clearInterval(repeticion);
}
It is a small simulation, since this will later work with real answers from a server and with another function.
I tried to do all this with a do-while, but logically the theme of the timer was not compatible. If someone knows how it also serves as an alternative solution.
How can I optimize my code and correct what is missing? Thanks