繁体   English   中英

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

[英]call a function after the setTimeout finishes execution- Javascript

我有一个场景,我想在执行三个函数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')
}

任何帮助,将不胜感激。

你可以这样做

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

你可以使用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) 

您可能需要一些全局变量/对象来保存执行每个函数的状态,并在最后检查是否可以启动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); 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM