What is JavaScript Version of Sleep()

Programming languages have their way of making the program stop for some seconds or milliseconds. For example, if you use PHP language, you should call sleep() function to make the program pause execution for 3 seconds.

Though JavaScript does not have a sleep function, due to the introduction of Promises and async/await in ES2018, we can end up causing the function to sleep.

JavaScript does not pause the whole program execution as other languages do. It only makes the function sleep.
const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

Next, you can use then callback:

sleep(1000).then(() => {
  //some things
})

Or use it in async function:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <script>
      function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      const doSomething = async() => {
        document.write('Wait for 2 seconds!');
        await sleep(2000)
        document.write('After 2 seconds!');
      }
      doSomething();
    </script>
  </body>
</html>
The await operator can only be used in async function and only pauses the current async function.

Promise

The Promise is an object that represents the completion or failure of the asynchronous operation and its output value.

The Promise can be in three states: pending, meaning the initial state, fulfilled when the operation is completed successfully, and rejected, meaning that the operation is failed.

Async/Await

The await operator makes the async function execution halt until a Promise is settled, and resume execution after fulfillment of Promise. The value of await is that of the fulfilled Promise. In case of rejection of Promise, the await throws the rejected value. If the value of the expression following await is not a Promise, it becomes a resolved Promise.

Do you find this helpful?

Related articles