Wait for the function to finish (using setInterval) and execute the following function

how to run the following function after the first execution using setInterval?

eg:

step1();
step2();

setInterval(step1, 1000).done(function() { 
    setInterval(step2, 1000).done( /* next step */);
});

      

please help me with a solution!

+3


source to share


3 answers


You can use a simple flag to accomplish this. See example below:



var flag = true;

function step1() {
  console.log('title');
}

function step2() {
  console.log('subtitle');
}

function wrapper() {
  if(flag) {
    step1();
  } else {
    step2();
  }
  flag = !flag;
}

setInterval(wrapper, 30000);

      

+1


source


If you want to bind functions on completion, you can use callback functions.

Example:

 function first(callback) {
      console.log('Running first');

      if (callback) {
           callback();
      }
 }

 function second() {
      console.log('Running second function');
 }

 first(second);

      



The first function checks if a callback is being used and then runs. If there is no callback function, nothing happens. This way you can link functions. You can also use anonymous functions.

 first(function () {
      console.log('This function that will run after the first one);
 });

      

If you are using setTimeout (), you cannot be sure if the previous function completed. The best way would be to use promises.
Understanding Promises
  Hope I understood your question correctly. Good luck!

0


source


First of all, setInterval cannot be executed by itself, it will run indefinitely unless you clear it with clearInterval.

But if you have some async action inside your function and you want to wait for it and then call another function, you can just promise it as Avraam Mavridis .

function step1() {
    var deferred = $.Deferred();
    setTimeout(function () {
        alert('I am step 1');
        deferred.resolve();
    }, 1000);
    return deferred.promise();
}

function step2() {
    alert('I am step 2');
}

step1().done(step2);

      

JsFiddle

0


source







All Articles