As an example, I want this code to output: // Delayed 3000s, Delayed 2000s, Delayed 1000s
But it's outputting the below because the loop moves faster than the promise. // Delayed 1000s, Delayed 2000s, Delayed 3000s
How can I write this code so it outputs in a sequential order?
// Delay function
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// main function
async function main(x) {
await sleep(x);
console.log(`Delayed ${x}s`);
}
let arr = [3000,2000,1000];
for (let i=0; i<arr.length; i++) {
main(arr[i]);
}