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 should stop, if it is 500 notify error and stop too. The request will be repeated every second (hence the use of setInterval although I don't know if I'm doing it correctly)
I also want it to try X times and also stop... I don't know how to implement it, could it be with a counter?
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 responses from a server and with another function.
I tried to do all this with a do-while, but logically the timer theme was not supported. If anyone knows how it also serves as a workaround.
How can I optimize my code and fix what is missing? Thank you
Code
Explanation
Based on what you state in your question, in order to perform a certain number of repetitions and not close, you could take into account the following:
First
We have declared some variables that will be outside the interval function:
In this case, changing the value of the variable
limite
, the code will be executed only that many times, for the example we leave 10.The variable
contador
is used to count the repetitions and this will be compared withlimite
each execution.The variable
bandera
will evaluate whether or not the desired value was found.Second
At the end of the function, we execute this statement:
What we indicate to the program in this case is something like:
So the body of the function will be executed multiple times, without the need to execute the same function multiple times.
When I have had to use setInterval I use it in the following way:
Now suppose we create a method that is executed every second (1000) called verifyCode() and should receive the code that in this case you generate with a Math.random():
I tried not to change the internal logic too much, it depends on what you want to do, I found the clearInterval() in the Stop setInterval call