published: 13 Jun 2022
2 min read
How to delay or sleep a JavaScript function
Many programming languages provide a sleep()
function that pauses the execution of the code for a certain amount of time. For example, in Java, you can use the Thread.sleep(2 * 1000)
to halt the current thread execution for 2 seconds.
Similarly, PHP has sleep(2)
, and Python has time.sleep(2)
to make the program stops for 2 seconds.
However, this functionality is not available in JavaScript due to its asynchronous execution model. But after the introduction of promises in ES6, we can easily implement such a feature in JavaScript to make a function sleep:
const sleep = (ms) => {
return new Promise((resolve, reject) => setTimeout(resolve, ms));
};
If you are using Node.js, just use the promisify
utility:
const { promisify } = require('util');
const sleep = promisify(setTimeout);
Now you can use the above sleep()
function with the then
callback:
console.log('Start time -> ${new Date().toISOString()}');
sleep(2 * 1000)
.then(() => console.log('After 2s -> ${new Date().toISOString()}'))
.then(() => sleep(2 * 1000))
.then(() => console.log('After 4s -> ${new Date().toISOString()}'));
// Start time -> 2021-10-02T08:35:31.993Z
// After 2s -> 2021-10-02T08:35:34.002Z
// After 4s -> 2021-10-02T08:35:36.004Z
For better readability, you can replace the then()
callbacks with async/await as shown below:
const timer = async () => {
console.log('Start time -> ${new Date().toISOString()}');
// Wait 2 seconds
await sleep(2 * 1000);
console.log('After 2s -> ${new Date().toISOString()}');
// Wait 2 more seconds
await sleep(2 * 1000);
console.log('After 4s -> ${new Date().toISOString()}');
};
timer();
// Start time -> 2021-10-02T08:42:34.754Z
// After 2s -> 2021-10-02T08:42:36.763Z
// After 4s -> 2021-10-02T08:42:38.764Z
Remember that due to the asynchronous nature of JavaScript, it is not possible to stop the entire program execution. Therefore, the above sleep()
method will only suspend the execution of the function where you'll call it.
Are we missing something? Help us improve this article. Reach out to us.
How to delay or sleep a JavaScript function
Many programming languages provide a sleep()
function that pauses the execution of the code for a certain amount of time. For example, in Java, you can use the Thread.sleep(2 * 1000)
to halt the current thread execution for 2 seconds.
Similarly, PHP has sleep(2)
, and Python has time.sleep(2)
to make the program stops for 2 seconds.
However, this functionality is not available in JavaScript due to its asynchronous execution model. But after the introduction of promises in ES6, we can easily implement such a feature in JavaScript to make a function sleep:
const sleep = (ms) => {
return new Promise((resolve, reject) => setTimeout(resolve, ms));
};
If you are using Node.js, just use the promisify
utility:
const { promisify } = require('util');
const sleep = promisify(setTimeout);
Now you can use the above sleep()
function with the then
callback:
console.log('Start time -> ${new Date().toISOString()}');
sleep(2 * 1000)
.then(() => console.log('After 2s -> ${new Date().toISOString()}'))
.then(() => sleep(2 * 1000))
.then(() => console.log('After 4s -> ${new Date().toISOString()}'));
// Start time -> 2021-10-02T08:35:31.993Z
// After 2s -> 2021-10-02T08:35:34.002Z
// After 4s -> 2021-10-02T08:35:36.004Z
For better readability, you can replace the then()
callbacks with async/await as shown below:
const timer = async () => {
console.log('Start time -> ${new Date().toISOString()}');
// Wait 2 seconds
await sleep(2 * 1000);
console.log('After 2s -> ${new Date().toISOString()}');
// Wait 2 more seconds
await sleep(2 * 1000);
console.log('After 4s -> ${new Date().toISOString()}');
};
timer();
// Start time -> 2021-10-02T08:42:34.754Z
// After 2s -> 2021-10-02T08:42:36.763Z
// After 4s -> 2021-10-02T08:42:38.764Z
Remember that due to the asynchronous nature of JavaScript, it is not possible to stop the entire program execution. Therefore, the above sleep()
method will only suspend the execution of the function where you'll call it.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur