js sleep function: JavaScript Sleep

As JavaScript has no sleep function, how to perform sleep function in js? Let’s see.

Sleep function in any programming language is used to pause or delay the execution of the programs for a certain period of time. The sleep function is often used to introduce a delay between two consecutive operations or to control the timing of a process.

Often time we need this sleep() function in our programs and is useful in scenarios where we need to synchronize multiple threads or processes.

For example: In a web scraping application, we need to pause our program between requests to avoid overloading the server. or in a game, we may need to introduce a small delay between two frames to give the player time to react to changes on the screen.

We have different methods and ways to implement this sleep method in different languages like in Python, we have time.sleep() function to introduce a delay. In C++, we can use the std::this_thread::sleep_for() function to pause execution for a specific duration.

The sad part is that JavaScript does not have a built-in sleep function. To achieve sleep function in JS, we have to use various other tricks and methods. One such method is setTimeout.

Sleep function in JS using setTimeout

Let’s see an example of how to use setTimeout to pause the execution of code for a certain amount of time:

setTimeout(function() {
  console.log('This message will be printed after a 2 second delay.');
}, 4000);

In this example, the setTimeout() function is used to delay the execution of an anonymous function for 2 seconds. After the delay, the function will be executed, and the message “This message will be printed after a 4 second delay.” will be printed to the console.

Sleep function in JS using Promise

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

async function example() {
  await sleep(2000); // Pause for 2 seconds
  console.log('This message will be printed after a 2 second delay.');


In this example, the sleep() function returns a Promise that resolves after the specified number of milliseconds. The example() function uses the await keyword to pause its execution for 2 seconds before printing the delayed message to the console.

Related posts

JavaScript Confirm() Method
For Each Method Javascript
JavaScript Array slice()
setTimeout Javascript