Loop with timer and conditions (Javascript)

4

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

    
asked by Norak 23.08.2017 в 13:34
source

2 answers

6

Code

/* Arreglo de errores */
var arreglo = [
  200, 204, 500, 404
];

/* Limite de repeticiones */
var limite = 10;

/* Contador de repeticiones */
var contador = 0;

/* Bandera */
var encontrado = false;

/* Interval */
var intervalo = setInterval(function() {

  var resultado = arreglo[Math.floor(Math.random() * arreglo.length)];

  if (resultado == 200) {
    console.log("HTTP 200! Encontrado!");
    encontrado = true;

  } else if (resultado == 500) {
    console.log("HTTP 500! Error interno del servidor");
    encontrado = true;

  } else if (resultado == 204) {
    console.log("HTTP 204!");

  } else if (resultado == 404) {
    console.log("HTTP 404!");
  }

  if (encontrado === true && contador >= limite) {
    stopFunction();
  }

  contador++;

}, 1000);

function stopFunction() {
  clearInterval(intervalo);
}

Explanation

Based on what you explain in your question, in order to make a certain number of repetitions and not to close, you could take into account the following:

First

We have declared some variables that will be outside the function of the interval:

/* Arreglo de errores */
var arreglo = [
  200, 204, 500, 404
];

/* Limite de repeticiones */
var limite = 10;

/* Contador de repeticiones */
var contador = 0;

/* Bandera */
var encontrado = false;

In this case changing the value of the variable limite , the code will be executed only that number of times, for the example we leave 10.

The variable contador is used to count the repetitions and this will be compared with limite in each execution.

The variable bandera will evaluate if the desired value was found or not.

Second

At the end of the function, we execute this sentence:

  if (encontrado === true && contador >= limite) {
    stopFunction();
  }

What we indicate to the program in this case is something like:

  

If you find any value and if you reach the limit, stop this program.

Thus the body of the function will be executed multiple times, without the need to execute the same function multiple times.

    
answered by 23.08.2017 / 15:04
source
2

When I had to use setInterval I use it in the following way:

var refreshInterval =  window.setInterval(function(){
   //Aquí puedes poner el Math.random()
/* lo que quieras que se ejecute */ verifyCode();  }, 
  /* El intervalo de tiempo */  1000);

Now let's suppose that we create a method that is executed every second (1000) called verifyCode () and must receive the code that in this case you generate with a Math.random ():

function verifyCode(rand){
   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!");
   }

   if (encontrado === true) {
            clearInterval(refreshInterval);
  }
 }

I tried not to change much the internal logic, it is already depending on what you want to do, the clearInterval () I found it in Stop setInterval call

    
answered by 23.08.2017 в 15:10