# How to make your JavaScript functions sleep

> Learn how to make a JavaScript function sleep for a set time, since the language has no native sleep, by wrapping setTimeout in a promise and using async/await.

Author: Flavio Copes | Published: 2018-07-23 | Updated: 2020-05-10 | Canonical: https://flaviocopes.com/javascript-sleep/

Sometimes you want your function to pause execution for a fixed amount of seconds or milliseconds.

In a programming language like C or PHP, you'd call `sleep(2)` to make the program halt for 2 seconds. Java has `Thread.sleep(2000)`, [Python](https://flaviocopes.com/python-introduction/) has `time.sleep(2)`, Go has `time.Sleep(2 * time.Second)`.

[JavaScript](https://flaviocopes.com/javascript/) does not have a native sleep function, but thanks to the introduction of promises (and async/await in ES2018) we can implement such feature in a very nice and readable way, to make your functions sleep:

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

or, in [Node.js](https://flaviocopes.com/nodejs/), simpler:

```js
const { promisify } = require('util')
const sleep = promisify(setTimeout)
```

> See more on [promisify](https://flaviocopes.com/node-promisify/)

You can now use this with the `then` callback:

```js
sleep(500).then(() => {
  //do stuff
})
```

Or use it in an async function:

```js
const doSomething = async () => {
  await sleep(2000)
  //do stuff
}

doSomething()
```

Remember that due to how JavaScript works (read more about [the event loop](https://flaviocopes.com/javascript-event-loop/)), this does not pause the entire program execution like it might happen in other languages, but instead only your function sleeps.

You can apply the same concept to a loop:

```js
const list = [1, 2, 3, 4]
const doSomething = async () => {
  for (const item of list) {
    await sleep(2000)
    console.log('🦄')    
  }
}

doSomething()
```
