Categories
JavaScript Answers

How to sleep the thread in Node.js without affecting other threads?

Spread the love

To sleep the thread in Node.js without affecting other threads, we use the setTimeout function.

For instance, we write

const snooze = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const example = async () => {
  console.log("About to snooze without halting the event loop...");
  await snooze(1000);
  console.log("done!");
};

example();

to define the snooze function.

In it, we return a promise that calls setTimeout with resolve as its callback after ms milliseconds to settle the promise after ms milliseconds.

Then we call snooze in the example function and use await to wait for the promise to finish.

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 *