How do you do sleep() in javascript? Well, there’s no native function called sleep but we can create our own and use it in our code just like we do sleep in PHP, C, and other programming languages.

To create a Javascript Sleep function we will use a function that returns a promise.

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

You can now use the sleep function after setTimeout runs it will resolve the function and you can use “then” to run whatever you want. Again this is not a native sleep function but we are simulating the effects.

sleep(1000).then(() => {
  console.log('running after 1 second')

We can also use an async function to achieve the same results then put the sleep function inside with an await on the sleep function.

const runCode = async () => {
  await sleep(1000)
  console.log('running after 1 second')


As you guys can see it’s not exactly apples to apples comparing it to languages like PHP but at least we are able to get similar results.

If you enjoyed this tutorial make sure you check out the courses at CodingPhase. Over 40 courses for $20 bucks click here to try them out for 50% OFF.