[英]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. 非常感谢。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.