Categories
JavaScript Answers

How to create a sleep or delay in Node.js that is not blocking with JavaScript?

Spread the love

Sometimes, we want to create a sleep or delay in Node.js that is not blocking with JavaScript.

In this article, we’ll look at how to create a sleep or delay in Node.js that is not blocking with JavaScript.

How to create a sleep or delay in Node.js that is not blocking with JavaScript?

To create a sleep or delay in Node.js that is not blocking with JavaScript, we can use a promise.

For instance, we write

const sleep = (millis) => {
  return new Promise((resolve) => setTimeout(resolve, millis));
};

const test = async () => {
  await sleep(1000);
  console.log("one second has elapsed");
};

to define the sleep function that returns a promise that calls setTimeout which calls resolve after millis milliseconds.

Then we call sleep in test with 1000 to pause for 1000 milliseconds.

Conclusion

To create a sleep or delay in Node.js that is not blocking with JavaScript, we can use a promise.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *