W3docs

What is JavaScript Version of Sleep()

The tutorial provides information about JavaScript version of the sleep() which makes the function pause execution for specified seconds of milliseconds.

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 <kbd class="highlighted">sleep()</kbd> 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 ES2015 and ES2017, we can simulate a sleep function.

Info

JavaScript does not pause the whole program execution as other languages do. It only makes the function sleep.

JavaScript Promise

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

Next, you can use <kbd class="highlighted">then callback</kbd>:

JavaScript Promise Callback

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

Or use it in async function:

JavaScript 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>
Warning

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.