Mike
Mike

Reputation: 279

Simplistic Way to Execute One Function (Which Contains setInterval) Before Another Function

I have three functions and I want to execute one after another. my three functions are A_rray(), Counter(), Main_Function(N,A), I have condition for Main_Function(N,A) based on A_rray(), once that part is executed, then I want to wait Counter() as below-

        if (A_rray().length!=0){
                           Main_Function(500,A_rray());
                              }
else{console.log('Number = ',A_rray().length)}
Counter();

Functions are-

function A_rray(){ D=[1,2];return D;}  
function  Counter(){console.log('Done!');}
function  Main_Function(N,A){
    var counter = 0;
    var interval = setInterval(function() {
        counter++;
        if (counter === A.length) {
            clearInterval(interval);
        }
        console.log(counter, 'iteration')
    }, N)                  }

But the problem is, Counter() function executes first, then the condition and other parts, this is probably because setInterval.

I tried some approaches written on Stack Overflow, but those didn't work since I am a beginner.

Is there a simplistic way to to execute first function Main_Function(N,A) based on Array(),then execute Counter() efficiently?

Upvotes: 1

Views: 32

Answers (2)

Harry Chang
Harry Chang

Reputation: 389

You can return a Promise which will resolve if clearInterval is called from Main_Function(N,A). Therefore, you can wait Main_Function(N,A) to finish, and then execute Counter() as desired.

(async() => {
  if (Array().length != 0) {
    await Main_Function(500, Array());
  } else {
    console.log('Number = ', Array().length)
  }
  Counter();
})();

function Array() {
  D = [1, 2];
  return D;
}

function Counter() {
  console.log('Done!');
}

function Main_Function(N, A) {
  return new Promise(resolve => {
    var counter = 0;
    var interval = setInterval(function() {
      counter++;
      if (counter === A.length) {
        clearInterval(interval);
        resolve();
      }
      console.log(counter, 'iteration');
    }, N);
  });
}

Upvotes: 1

lidlbobbytables
lidlbobbytables

Reputation: 490

One of the more simpler ways of doing this would be to edit your MAIN_FUNCTION so that you call Counter from inside there.

function MAIN_FUNCTION(N,A) {
  var counter = 0;
    var interval = setInterval(function() {
        counter++;
        console.log(counter, 'iteration');
        if (counter === A.length) {
            clearInterval(interval);
            Counter();
        }
    }, N);
}

And then getting rid of the other Counter Call from the execution bit

This will ensure that Counter is only run after the last iteration of the interval

Few notes:

  • Seeing that Counter is only logging you could simply replace the call with the log call
  • Calling a function Array is overwriting a default function of javascript that is the constructor of the Array class

Upvotes: 1

Related Questions