How to Sleep in node.js?
In Node.js, there is no built-in sleep
function like in some other programming languages. However, you can use the setTimeout
function to simulate a sleep-like behavior. Here's a simple example:
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function example() {
console.log('Start');
// Sleep for 3 seconds
await sleep(3000);
console.log('End');
}
example();
In this example:
- The
sleep
function returns a Promise that resolves after a specified number of milliseconds. - The
example
function is an asynchronous function that usesawait
to pause execution for the specified duration. - The
example
function sleeps for 3 seconds (3000 milliseconds) between the "Start" and "End" log statements.
This approach is non-blocking and works well with the asynchronous nature of Node.js. If you need a synchronous sleep in a specific context, you may need to reconsider your design to leverage asynchronous patterns, as synchronous sleep can block the event loop and negatively impact the performance of your application.
-
How to Read Package Version in node.js Code?
To read the package version in Node.js code, you can use the require function to import the package.json file and access the version property. Here's an example: Assuming your project structure loo...
Questions -
Execute a Command Line Binary with node.js
You can execute a command line binary in Node.js using the child_process module. Here's a simple example: const { exec } = require('child_process'); const binaryPath = '/path/to/your/binary'; // Re...
Questions
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github