I have 4 functions and I’m trying to run each of them 4 seconds apart.
With my below code there is only a 4 second gap between StepOne and StepTwo, thereafter there is no gap between the rest of the steps. What am I doing wrong?
/* Steps */
function StepOne() {
console.log("Step One");
}
function StepTwo() {
console.log("Step Two");
}
function StepThree() {
console.log("Step Three");
}
function StepFour() {
console.log("Step Four");
}
/* Sleep */
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/* Run each function 4 seconds apart */
StepOne();
sleep(4000).then(() => { StepTwo(); });
sleep(4000).then(() => { StepThree(); });
sleep(4000).then(() => { StepFour(); });
3
Answers
The reason you’re not seeing a gap between StepTwo, StepThree, and StepFour is that the sleep function is asynchronous, and all the sleep promises are being executed one after another without waiting for each other to finish.
You need to ensure that each sleep promise starts after the previous one has completed. You can do this by chaining the promises using
then():
The issue with your code is that you are initiating the sleep function for each step one after the other, but you’re not accounting for the cumulative delay. Each
sleep
call starts a new timer, so they’re not synchronized as you expect.To fix this, you should chain the
then
calls so that each step executes after the previous one has finished. Here’s the corrected version of your code:In this version, each
then
call waits for the previous one to complete before starting the next one. This ensures that each step executes 4 seconds after the previous one.The
then
functions are not chained as they are supposed to be. Cleaner approach would be usingasync/ await
like below