user8040987
user8040987

Reputation:

How to call a function after all setTimeout functions is done

How to call the second function after the all previous functions is done.

function first() {
    // code here
    setTimeout( function() {
        // code here
    }, 1000);

    // code here
    setTimeout( function() {
        // code here
    }, 3000);

    // code here
    setTimeout( function() {
        // code here
    }, 3800);
}

function second() {
    // code here
}

first();
first();
second();
first();
second();

It seems all functions executed in the same time.
Thanks a lot.

Upvotes: 1

Views: 2117

Answers (1)

Michał Sałaciński
Michał Sałaciński

Reputation: 2266

If you need to call a specific function after the last timeout, I think this will point you in the right direction. Of course, it can be written better, with reusable "class" etc.

function myTimeout(f,t) {
    var p = new Promise(resolve=>{
      setTimeout(()=>{
        resolve(f.apply(this,[]));
    }, t);
    });
    

    //return p.promise(); 
  return p;
}

function first() {
    var numberOfTimeouts = 3
    // code here
    myTimeout(()=>{
        // code here
        console.log('a')
    }, 1000).then(()=>{
      numberOfTimeouts--;
      if (!numberOfTimeouts) second()
    });

    // code here
    myTimeout( function() {
        console.log('b')
    }, 3000).then(()=>{
      numberOfTimeouts--;
      if (!numberOfTimeouts) second()
    });

    // code here
    myTimeout( function() {
       console.log('c')
    }, 3800).then(()=>{
      numberOfTimeouts--;
      if (!numberOfTimeouts) second()
    });
}

function second() {
   console.log('d')
}

first();

Upvotes: 1

Related Questions