Suhas Kulkarni
Suhas Kulkarni

Reputation: 263

How to execute synchronously using setInterval or setTimeOut?

I have a function as below:

function foo(args1, args2, retry)
{
    if (retry <= 0)
        return false;

    var isDone = callAnotherFunction(args1, args2);

    if(!isDone) {
       setInterval(function () {
           foo(args1, args2, retry-1);
       },
       2000);
    }
    else
      return true;
}

So I am not sure if the above implementation is correct. But I need to use this function in another function. And use the above function in an if block to decide if the other statement needs to be executed. Below is the usage of the above function.

function useIt(args1, args2)
{
    // Other code
    let store = function() {
       if(!foo(args1, args2, 5)) {
           cleanStorage(args1, args2);
           return;
       }
}

So the problem is in function useIt(), cleanStorage() does not wait for foo() to be executed if I am using setInterval or setTimeOut. So how do I need to implement the function foo() ? Kindly help me.

Upvotes: 3

Views: 7751

Answers (2)

thedude
thedude

Reputation: 9814

consider using promises

foo can be rewritten like this (I've replace setInterval with setTimeout):

function foo(args1, args2, retry) {
  return new Promise(function (resolve, reject) {
    if (retry <= 0)
      reject();

    var isDone = callAnotherFunction(args1, args2);

    if (!isDone) {
      setTimeout(function () {
        resolve(foo(args1, args2, retry - 1));
      }, 2000);
    }
    else
      resolve(true);
  })
}

and then use it like this:

function useIt(args1, args2) {
  // Other code
  let store = function () {
    foo(args1, args2, 5).then(function () {
      cleanStorage(args1, args2);
    });
  }
}

Upvotes: 7

suvroc
suvroc

Reputation: 3062

You should use Promises to do this

Something like this:

function foo(args1, args2, retry)
{
    return new Promise(function(resolve, reject) {
    if (retry <= 0)
        reject();

    var isDone = callAnotherFunction(args1, args2);

    if(!isDone) {
       setInterval(function () {
            retry = retry - 1;
            isDone = callAnotherFunction(args1, args2);
            if (isDone)
               resolve();
       },
       2000);
    }
    else
      resolve();
  }
}

function useIt(args1, args2)
{
    // Other code
    let store = function() {
    foo(args1, args2, 5).then(result => {
            cleanStorage(args1, args2);
            return;
        }
    }
}

Upvotes: 6

Related Questions