Until Async/Await
when we needed to make a recurrent thing N times every X seconds we had the choice between a for loop that wrap a settimeout
or to use a wrapper around setinterval
to count the number of times it was executed and clear it.
But with async await is it okay to do this:
async function newFashion() {
for (let i = 0; i < 10; i++) {
console.log(i);
await sleep(1000);
}
console.log("Finish");
}
newFashion(); // 0 1 2 3 4 5 6 7 8 9 Finish
function oldFashion() {
for (let i = 0; i < 10; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
console.log("Finish");
}
oldFashion(); // Finish 0 1 2 3 4 5 6 7 8 9
function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
I know that the two don't behave the same. oldFashion()
doesn't actually "pause" in the loop, but actually call the 10 setTimeout()
while iterating, so basically he fills the event loop with 10 setTimeout()
.
newFashion()
however behaves as it should be, he "stop" iterating when he hit the await, but I'm not sure exactly how that work.
So what is better, filling the event loop with N setTimeout()
, or awaiting one after the other? And what is actually happening in newFashion()
?
EDIT: To be a little more specific, what is the gain of each method in terms of performance? When N is small? When N is huge?