javascript – Loop in function calling itself

Question:

I need to create a purposeful loop to check if a variable reached the desired value, the idea is to create a function that will have an if inside it, which checks if cont == 4 in case 4 is the number of iterations before the function, if it is it continues the process if it is not yet 4 it setInterval a setInterval passing the função in 500 milissegundos as a parameter.

Below the code:

      function verificaCont(){

        if(data.cont == 4){
          console.log(data);
        }else{
          setInterval(verificaCont(), 500); 
        }

      }

The error that happens when executing this function is:

Uncaught SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.

How can I solve this problem ? or is there something so i can have to generate a loop ?

REASON:
I need this loop because I'm doing an activity that intends to save several data in an object, between these data it may be necessary to go to the database, but the database used is asynchronous, for this reason I need a loop so that I have time to fill the whole object.

Answer:

setInteval is a function that executes a certain function always at a time interval.

If you want to do it this way you should use setTimeout which runs only once after the break.

Code

function verificaCont(){
    if(data.cont == 4){
        console.log(data);
    }else{
        setTimeout(function(){
            verificaCont();
        }, 500);
    }
}

Alternative

function verificaCont(){
    this.checkCount = setInterval(function(){ 
        if(data.cont == 4){
            clearInterval(this.checkCount);
        }
    }, 500);
}
Scroll to Top