Loop into function calling itself

Asked

Viewed 1,633 times

3

I need to create a purposeful loop to check if a variable has reached the desired value, the idea is to create a function that inside it will have a if, which turns out to be 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 he of the one setInterval passing by parameter to função in 500 milissegundos.

Below the code:

      function verificaCont(){

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

      }

The error that happens when performing 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 I can have to generate a loop ?

MOTIVE:
I need this loop because I am doing an activity that intends to save in a multiple object data, between these data may be necessary to go to the database, but the database used is asynchronous, for this reason I need a loop to allow time to fill the whole object.

  • Updates the question with the for code you have.

  • @Renan, JS was made to work asynchronously, could you tell what is the server-side language used to access the database? because I believe this loop is unnecessary, and what it needs is a callback function.

  • @Tobymosque I use Indexeddb, and when I go to the search bank it continues to pass to the bottom line, and when I enter it does not enter the data. Even if the data is in the object.

  • @Renanrodrigues, when you make a request to an objectStore, you have two events. " sucess" and "error", so you can perform a callback function in the request "sucess". If you are making multiple requests, then create an internal counter, and when it reaches the number of requests made, you call the callback function.

  • so it’s interesting that you add the question to your code snippet that accesses Indexeddb, so I can suggest a better way to work with it.

  • @Tobymosque how would it look ? would you show me an answer ?

Show 1 more comment

2 answers

7

The setInteval is a function that performs a certain function at all times in an interval of time.

If you want to do it this way you should use the setTimeout that performs only once after the interval.

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);
}
  • your code is giving the following error: Uncaught Syntaxerror: In Strict mode code, functions can only be declared at top level or immediately Within Another Function.

  • @Renanrodrigues sorry, I thought it was possible to call the function directly in the first parameter, but apparently it should be called within the function.

1


Like I said, it’s to give you a full answer, it would be interesting to post your code with Indexeddb, so I’ll just post a generic response.

for example, let’s imagine two Tables, Users and People, where Users have a 1:N relationship with People and we only want the User Login and Person Name.

var transaction = db.transaction(["usuarios", "pessoas"]);
var usuarioStore = transaction.objectStore("usuarios");
var pessoaStore = transaction.objectStore("pessoas");

var UsuarioModel = function(usuarioID, callback) {
  var self = this;
  self.UsuarioID = usuarioID;

  var usuarioRequest = usuarioStore.get(self.UsuarioID);
  usuarioRequest.onsucess = function (event) {
    self.Logon = usuarioRequest.result.Logon;

    var pessoaRequest = pessoaStore.get(usuarioRequest.result.PessoaID);
    pessoaRequest.onsucess = function (event) {
      self.Nome = pessoaRequest.result.Nome;
      callback();
    }
  }    
}

var usuarioModel = new UsuarioModel(35, function () {
  console.log(usuarioModel);
});

In the above example, the callback will be executed the Name is recovered.

Now let’s imagine a second scenario, the entity Users and People are independent, but need to wait for the return of the two requests to execute some code.

var transaction = db.transaction(["usuarios", "pessoas"]);
var usuarioStore = transaction.objectStore("usuarios");
var pessoaStore = transaction.objectStore("pessoas");

var UsuarioModel = function(usuarioID, pessoaID, callback) {
  var self = this;
  var sucessos = 0;
  var execCallBack = function () {
    sucessos++;
    if (sucessos == 2) {
      callback();
    }
  } 

  self.UsuarioID = usuarioID;
  self.PessoaID = pessoaID;

  var usuarioRequest = usuarioStore.get(self.UsuarioID);
  usuarioRequest.onsucess = function (event) {
    self.Logon = usuarioRequest.result.Logon;
    execCallBack();
  }    

  var pessoaRequest = pessoaStore.get(self.PessoaID);
  pessoaRequest.onsucess = function (event) {
    self.Nome = pessoaRequest.result.Nome;
    execCallBack();
  }
}

var usuarioModel = new UsuarioModel(35, 58, function () {
  console.log(usuarioModel);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.