Home > Blockchain >  How to execute a function after another function has executed a given number of times?
How to execute a function after another function has executed a given number of times?

Time:10-28

Hi,

I have a function like this

checkconnection();

I want to execute it 5 times before this function below triggers:

console.log('cant connect. Try again later');

How can I do that?

Thank you.

CodePudding user response:

You can use a recursive function and a counter variable that counts up to 5.

let cntr = 1;

function checkconnection(){
   if(cntr == 5){
      console.log('cant connect. Try again later');
   }
   else{
     cntr   ;
     checkconnection();
   }
}

checkconnection();

CodePudding user response:

You can make another function out of it using another function... this technique is called memoization.

function checkConnection() {
  console.log("checking connnection");
}

// let's limit it to 5
var checkConnection = limiter(checkConnection);

function limiter(func, times) {
  var i = 0
  times = times || 5
  return function() {
    if (i   < times) {
      func()
    } else {
      console.log("stop running after 5 times");
    }
  }
}

for (var i = 0; i < 10; i  ) {
  checkConnection();
}

  • Related