Make javascript functions sleep

Learn how to make functions sleep or pause for a given duration in javascript.

There are times when we want our javascript functions to sleep for a specific amount of time.

Many programming languages have inbuilt functions available which can halt the function execution for the given amount of time.

  • C or PHP: sleep(2)
  • JAVA: Thread.sleep(2000)
  • Python: time.sleep(2)
  • Go: time.Sleep(2 * time.Second)

Javascript does not have any inbuilt function for this, But thanks to the introduction of promises and async-await in ES2018, we can now implement such feature with out any hassle and use it seamlessly.

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
};

This will create a wrapper function which will resolve the promise after the given milliseconds.

We can use this to prevent function execution for certain amount of time.

sleep(500).then(() => {
  //do stuff
  console.log('I run after 500 milliseconds');
});

Or we can use the async-await syntax

const performAction = async () => {
  await sleep(2000)
  //do stuff
}

performAction();

This works well, however due to how javascript works this does not stop the entire program execution like it does in other programming languages, instead it will just make our current function sleep.