/

How to Implement a Sleep Function in JavaScript

How to Implement a Sleep Function in JavaScript

Learn how to create a sleep function in JavaScript to pause the execution of your functions for a specific amount of time.

There are scenarios where you might want your function to pause for a fixed number of seconds or milliseconds. In other programming languages like C or PHP, you could simply call sleep(2) to halt the program for 2 seconds. Similarly, Java provides Thread.sleep(2000), Python has time.sleep(2), and Go offers time.Sleep(2 * time.Second).

However, JavaScript lacks a built-in sleep function. Fortunately, with the introduction of promises and async/await in ES2018, we can implement this feature in an elegant and readable way:

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

In Node.js, you can simplify it further:

1
2
const { promisify } = require('util')
const sleep = promisify(setTimeout)

If you prefer using the then callback, you can use the sleep function like this:

1
2
3
sleep(500).then(() => {
// do stuff
})

Alternatively, you can utilize it in an async function:

1
2
3
4
5
6
const doSomething = async () => {
await sleep(2000)
// do stuff
}

doSomething()

Keep in mind that JavaScript’s event loop operates differently, so the sleep function does not pause the entire program execution like it would in other languages. Instead, it only halts the execution of your function.

You can apply the same concept to a loop:

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

doSomething()

Tags: JavaScript, sleep function, promises, async/await, event loop, Node.js