setTimeout(() => {console.log("this is the first message")}, 5000);
setTimeout(() => {console.log("this is the second message")}, 3000);
setTimeout(() => {console.log("this is the third message")}, 1000);
How can I make this code wait for the first function to finish before executing the second one or the function with less seconds?
CodePudding user response:
function delay(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
delay(1000)
.then(() => alert("Hello!"))
Also you can make it to async/await
CodePudding user response:
did someone say... async await
?
const wait = ms => new Promise(r => setTimeout(r, ms));
(async () => {
console.log("this is the first message");
await wait(5000);
console.log("this is the second message");
await wait(3000);
console.log("this is the third message");
await wait(1000);
})();