JavaScript does not have an inbuilt/native sleep function, but thanks to the introduction of promises (and async/await in ES2018), we can implement such features in an evident and precise way, to make your functions sleep.

JavaScript sleep

To make your functions sleep in JavaScript, use the combination of setTimeout() and Promise to delay your function execution in your intentional way.

Syntax

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

In this example, we are creating a sleep() function that takes **milliseconds **as a parameter.

The sleep function will create a new Promise that will resolve in given milliseconds, so until that, the execution will be paused. After resolving, it will start to continue the execution.

Example

// app.js

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

const list = [1, 2, 3, 4, 5]
const task = async () => {
  for (const item of list) {
    await sleep(1000);
    console.log('Yello, D\'oh');
  }
}

task();

In this example, first, we have defined a sleep function. We will call the sleep() function when we need to sleep the specific function.

Now, in our code, that specific function is the **task(). **So, we will use **sleep() **function in task() function to sleep.

Here, we used async-await because sleep() will return the promise. The word “async” before a function means one simple thing: a function always returns a promise. 2. The keyword “await” makes JavaScript wait until that promise settles and returns its result.

We defined an array list that can be helpful to create a loop.

The task() function logs the Yello, D’oh value one by one within the gap of 1 second. So, for one second, the function goes to sleep, and after the promise is resolved, it will log the next time the same string, and then again, goes to sleep for 1 second, and so on.

#javascript

How to Make your Functions Sleep in JavaScript
2.20 GEEK