在setTimeout完成执行后调用函数-Javascript

时间:2018-02-19 12:32:33

标签: javascript jquery

我有一个场景,我想在执行三个函数a(),b(),c()之后调用函数d(),这三个函数并行执行。

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

执行完所有函数后,我想让下面的函数d()执行

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

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:5)

你可以这样做



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(); 
});




答案 1 :(得分:2)

您可以使用Promise.all来执行此操作。

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)




答案 2 :(得分:1)

您可能需要一些全局变量/对象来保存执行每个函数的状态,并在最后检查是否可以启动d函数。例如:

// 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);

答案 3 :(得分:1)

只需定义一个有前途的计时器:

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

所以你可以这样做:

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

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