in ,

Javascript Sleep

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')
}

runCode()

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.

What do you think?

Written by CodingPhase

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading…

0

Comments

0 comments

CSS Selectors ~ +

The Difference Between the Plus Sign (+) and Tilde (~) in CSS

Adding Color and Styles to Console Logs