Shikha thakur
Shikha thakur

Reputation: 1289

call a function after the setTimeout finishes execution- Javascript

I have a scenario where I want to call the function d() after the execution of three functions a(), b(), c(), These three functions executes parallely.

setTimeout(function a(){ alert("Hello A"); a()}, 3000);
setTimeout(function b(){ alert("Hello B"); b()}, 3000);
setTimeout(function c(){ alert("Hello C"); c()}, 3000);

After getting all the functions executed I want the below function d() to get executed

function d(){
console.log('hello D')
}

Any help would be appreciated.

Upvotes: 3

Views: 6775

Answers (4)

Kiran Shinde
Kiran Shinde

Reputation: 5982

You can do this like

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(function a(){ alert("Hello A"); resolve();}, 3000);
})

var promise2 = new Promise(function(resolve, reject) {
    setTimeout(function b(){ alert("Hello B"); resolve();}, 3000);
})

var promise3 = new Promise(function(resolve, reject) {
    setTimeout(function c(){ alert("Hello C"); resolve();}, 3000);
})

Promise.all([promise1, promise2, promise3]).then(function() {
  function d(){
     console.log('hello D') 
  }
  d(); 
});

Upvotes: 9

A. Denis
A. Denis

Reputation: 562

You probably need some global variable/object to save state of executed each function and check at the end if you can start d function. Example:

// you probably need some global variable/object
oCheckedFunctions = { a:false, b:false, c:false };
function d(){
	alert('hello D')
}
function a(){ 
	alert("Hello A"); 
	oCheckedFunctions.a = true;
	checkAndTryForD();
}
function b(){ 
	alert("Hello B"); 
	oCheckedFunctions.b = true;
	checkAndTryForD();
}
function c(){ 
	alert("Hello C"); 
	oCheckedFunctions.c = true;
	checkAndTryForD();
}

function checkAndTryForD() {
	if (oCheckedFunctions.a && oCheckedFunctions.b && oCheckedFunctions.c) {
		d();
	}
}

// your functions
setTimeout(a, 3000);
setTimeout(b, 3000);
setTimeout(c, 3000);

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138267

Just define a promising timer once:

 const timer = ms => new Promise(res => setTimeout(res, ms));

So you can do:

 const log = v => _ => console.log(v);

 Promise.all([
  timer(3000).then(log("a")),
  timer(3000).then(log("b"))
 ]).then(log("c"));

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26370

You can use Promise.all to do that.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const a = new Promise( (resolve, reject) => setTimeout( () => {
					console.log("a is finished");
					resolve()
				}, 3000) ),
	  b = new Promise( (resolve, reject) => setTimeout( () => {
					console.log("b is finished");
					resolve()
				}, 1000) ),
	  c =  new Promise( (resolve, reject) => setTimeout( () => {
					console.log("c is finished");
					resolve()
				}, 2000) )

const d = () => console.log('hello D')

Promise.all( [a,b,c] ).then(d)

Upvotes: 3

Related Questions