Other answers here are of course correct.
But going forward into the future async code is much easier using async / await.
So below is a simple example,.. It initially looks longer, due to utility function delay, but as your program gets larger using async / await will make your code much easier to follow.
Another advantage here too, is only 1 setTimeout is created,. So potentially more resource friendly. You could also achieve using 1 setTimeout without async / await but would require chaining the setTimeout's making the code even harder to follow.
// utility function do delay,
// can be used again..
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
//await can only be called from async function.
//so lets just create run function to get things started.
async function run () {
for (let x = 0; x < 5; x++) {
await delay(800);
console.log(x,"x");
}
}
//lets get things started..
run ();