[英]How to call a function after all setTimeout 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();
似乎所有功能都在同一时间执行。
非常感谢。
如果您需要在上次超时后调用特定函数,我认为这将指向正确的方向。 当然,它可以写得更好,可重复使用“类”等。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.