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.

Top comments (0)