How To Create and Use sleep() Function In JavaScript Tutorial with Example?


JavaScript programming language does not provide a function named sleep() but it provides some alternative functions and techniques in order to sleep the code execution. In this tutorial, we will learn how to implement and use sleep() function in different ways.

JavaScript Do Not Provides sleep() Function Natively

As stated at the beginning of the post JavaScript programming language does not provides sleep() function exactly. But the sleep function can be implemented in different ways. When we try to run sleep() inside the browser we will get an error like Uncaught ReferenceError: sleep is not defined like below.

JavaScript Do Not Provides sleep() Function Natively
JavaScript Do Not Provides sleep() Function Natively

Create and Use sleep() Function with a Promise and setTimeout Function

We can implement or create and use the sleep function by using JavaScript Promise and setTimeout() function. We will provide the setTimeout() function and provide the time value we want to sleep. Let’s create the sleep() function with the following code snippet.

function sleep(time) {
   return new Promise(resolve => setTimeout(resolve, time));
}

We can use the newly created sleep() function like below. We will also add await before the sleep function. We will also add the time value we want to sleep which is in the millisecond unit. For example, if we want to sleep for 3 seconds we will provide 3000 to the new sleep function like below.

console.log("Before sleep"); await sleep(3000);console.log("After sleep");
Create and Use sleep() Function with a Promise and setTimeout Function
Create and Use sleep() Function with a Promise and setTimeout Function

Leave a Comment