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 | const sleep = (milliseconds) => { |
In Node.js, you can simplify it further:
1 | const { promisify } = require('util') |
If you prefer using the then
callback, you can use the sleep function like this:
1 | sleep(500).then(() => { |
Alternatively, you can utilize it in an async function:
1 | const doSomething = async () => { |
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 | const list = [1, 2, 3, 4] |
Tags: JavaScript, sleep function, promises, async/await, event loop, Node.js