问题
I need a simple way to wait for setTimeout code to finish executing and then run the code that comes after setTimeout. Now the code after loop containing setTimout is executing before loop/setTimout is finished executing.
for(let i = 0; i < 5; i++) {
setTimeout(function(){
console.log(i);
}, i*1000);
}
console.log("loop/timeout is done executing");
回答1:
setTimeout is by definition not synchronous - whatever you use to solve the issue will have to be asynchronous, there's no way around that.
The best way to achieve something like this is to use Promises instead, calling Promise.all on an array of the created promises:
(async () => {
await Promise.all(Array.from(
{ length: 5 },
(_, i) => new Promise(res => setTimeout(() => {
console.log(i);
res();
}, i * 1000))
));
console.log("loop/timeout is done executing");
})();
Although await is awaiting a Promise, and Promises aren't synchronous, if you're want the code to look flat so you can have the final console.log on the same indentation level as the main function block, this is probably the way to go.
回答2:
you can define a function and call that function inside the timeout
let currentForId = 0;
for(let i = 0; i < 5; i++) {
setTimeout(function(){
console.log(i);
if(++currentForId == 5)
calling("message");
}, i*1000);
}
function calling(msg){
console.log(msg);
console.log("loop/timeout is done executing");
}
来源:https://stackoverflow.com/questions/50918932/simple-way-to-synchronously-execute-code-after-settimout-code-is-done