How to add Node.js sleep function [Practical Examples]

How can we sleep or delay using Node.Js Javascript?

The Node.Js sleep function does not exist. However, there are different methods you can use to implement its functionality.

In programming languages like C, Ruby, or Python pausing or delaying function execution is pretty straightforward as you would only need to call the sleep function.

Advertisement

For instance, consider the following Python function:

import time
print(‘Print first’)
time.sleep(2)
print(‘Print after 2 seconds’’)

In this code, Print first is displayed first and then the function execution is paused for 2 seconds before the next line of code is executed.

If the sleep function existed, the delaying code in JavaScript could look like this:

function sleep () {
  // sleep for 2 seconds
  sleep(2000)
  console.log(‘Print after 2 seconds’)
}

But this wouldn’t work because JavaScript does not have a native sleep function. However, there are workarounds through which you can perform a time delay. To understand these workarounds, it is important to first understand how JavaScript executes code.

The following code fetches some fake data from a fake API.

fetch(‘https://reqres.in/api/users?page=2’)
  .then(res => res.json())
  .then(json => console.log(json.data[0]) )
console.log(‘This statement is printed first’)

If you run this code, the last line will be executed first and then the data from the API call will be displayed.

Advertisement

This is because the fetch function is asynchronous. When JavaScript fetches data from the API, it does not wait for the request to complete, or rather it does not wait for the responses to be sent back. Instead, it continues to the next line that does which is the console log statement to display ‘This statement is printed first’. Then when an event is emitted that the request has completed, it goes back and outputs the specified data.

If you are looking for a way to implement a delay, you might not need to use sleep().

 

Implementing a delay using setTimeout

 By using the if…else statement with the setTimeout function, you can pause the execution of your code for a certain time. The code below uses setTimeout to rerun a function if a certain condition is not met but only after waiting for 2 seconds.

function checkResponse () {
  if (apiResponse) {
    // Do something with response like updating UI
  } else {
    setTimeout(checkResponse, 2000); // try again in 2 seconds
  }
}

In this function, the setTimeout runs the function if no response exists after every 2 seconds.

Now consider a situation where you need to wait on other data. Using the above solution, you would need to chain a couple more else-if statements and in the end, you would end up with messy code. To simplify the above function, use async/await.

(async () => {
  const res = await checkResponse()
  const validatedRes = await validateResponse()
  console.log(validatedRes);
})();

In the code above, instead of pausing function execution to wait on a response, we use async/await to execute the code synchronously.

 

Implementing the Sleep() Function in Node.js

Method-1: Using setTimeout

The setTimeout() function is used to create a time delay before a certain block of code is executed. So why not use it to implement the sleep() function. First, consider this code that uses setTimeout to delay printing a simple statement on the console after 2 seconds

function sleep() {
   // prevent the statement in the callback function of 
   setTimeout from running before 2 seconds pass
   setTimeout(function(){ 
        console.log(‘Print after 2 seconds’)
    }, 2000);  
   console.log(‘This statement will be displayed immediately’)
}

When the above code is run, JavaScript first encounters the setTimeout function and adds it to the event queue. It then moves on to the next line of code and executes it. In this case, the last line in the function will be run, and ‘This statement will be displayed immediately’ will be displayed. When the specified time delay is up, the JavaScript VM picks it and executes the callback function. 

Advertisement

At first glance, this function seems like it works properly but it has some issues. If in the same event queue, we had a function that was more eligible for execution like a setTimeout function that had a lesser time delay, our setTimeout function would be delayed further. The above implementation is therefore not reliable.

To solve this problem,  you could use a while loop to block the execution of other functions until the time delay is up. This code uses the Date function to calculate the time left between the current time and the time after the delay. This is the time used to determine how long the function should be paused.

function sleep(delayMs) {
  let start = new Date().getTime();
  while (new Date().getTime() < start + delayMs) {
       // do something
  }
};

The above code has one major drawback, it is a very CPU-intensive solution. Remember that JavaScript is a single threaded language. The while loop will therefore block any other function from executing until its condition is met. For small delays like 2 seconds, this might not be a problem. But if you need your code to pause for a longer time, you might crash your program.        

 

Method-2: Using async/await                

To have a sleep function that does not block the whole program, you should use an async function. The code would look like this:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function test() {
  console.log('Sleeping for 2 seconds');
  await sleep(2000);
  console.log('Print statement after 2 seconds');
}

In this function, using the async function ensures that the only function that is paused is the current one. JavaScript is, therefore, free to execute the rest of the code until the async function returns.

The above function can also be implemented in a scenario that requires multiple delays.

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

async function sleepMany() {
  console.log("1");
  await sleep(1000);
  console.log("2");
  await sleep(2000);
  console.log("3");
}

In this function, after each statement is displayed in the console, the function pauses for the specified amount of time. Again, other functions in the script can be executed as this implementation is non-blocking.

 

Method-3: Using the Npm Sleep-promise Package

If you are looking to simply use a sleep function without writing the function itself, you can use the sleep-promise package from npm. To use it, you will need to install it.

npm install sleep-promise

To use sleep-promise, you only need to call it and pass in the time delay in milliseconds.

const sleep = require('sleep-promise');
(async () => {
    console.log("Printed immediately.");
    await sleep(2000);
    console.log("Printed after two seconds.");
})();

The above function is asynchronous and can run in the background while another block of code executes.

 

Conclusion

While other programming languages might have a native sleep function, the asynchronous nature of Node.JS means that it is non-blocking, and implementing a sleep function can become complicated. One thing to keep in mind with your implementation is that you should not block JavaScript from executing other code in the script when your sleep function is running.

 

Learn more

JavaScript version of sleep() on StackOverflow
Using the sleep-promise npm  package

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment