DEV Community

WangLiwen
WangLiwen

Posted on

Implement a true "sleep" function in Node.js

Node.js is a JavaScript runtime environment based on the Chrome V8 engine, utilizing a single-threaded, event-driven, and non-blocking I/O model. Since JavaScript is inherently single-threaded, the conventional thread sleep mechanism, such as Thread.sleep in Java, is not suitable for Node.js as it would block the entire event loop, thereby affecting the execution of all tasks.

However, if you wish to implement a "sleep-like" behavior without impeding the progress of other asynchronous operations, you can employ Promises along with setTimeout to simulate asynchronous waiting. This method allows the event loop to continue processing other tasks during the waiting period, emulating concurrent execution. Below is a straightforward example:

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


async function yourAsyncFunction() {
    console.log('Execution begins');
    await sleep(2000); // Simulates a "sleep" for 2 seconds
    console.log('Resumes after 2 seconds');
}

yourAsyncFunction();
console.log('This line prints immediately');
Enter fullscreen mode Exit fullscreen mode

In this example, the sleep function returns a Promise that resolves after a certain number of milliseconds, enabling the use of the await keyword within an asynchronous function to "pause" without blocking the rest of the code. The statement console.log('This line prints immediately') executes right away, demonstrating the non-blocking nature.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay