What is the best way to pause execution in Node.js?
I’m developing a console script for personal use and need to pause execution for a specific period of time. From my research, Node.js doesn’t have a built-in way to “sleep” as required.
I’ve seen approaches like:
setTimeout(function() {
}, 3000);
However, I need everything after this line to execute only after the wait period.
For example:
console.log('Welcome to my console,');
some-wait-code-here-for-ten-seconds...
console.log('Blah blah blah blah extra-blah');
I’ve also come across yield sleep(2000)
, but Node.js doesn’t recognize it.
How can I implement a proper nodejs sleep function to pause execution efficiently?
This is the cleanest and most modern approach to handle a delay in Node.js. It makes use of async/await along with a Promise that resolves after a delay:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log('Welcome to my console,');
await sleep(10000); // Wait for 10 seconds
console.log('Blah blah blah blah extra-blah');
}
main();
You can use the setTimeout method along with a callback function, but this doesn’t give you the same synchronous-looking code as async/await. It’s still effective for simple use cases:
console.log('Welcome to my console,');
setTimeout(() => {
console.log('Blah blah blah blah extra-blah');
}, 10000
If you prefer to avoid async/await and still want to handle delays in a cleaner way than callbacks, you can create a Promise with a delay and use .then() to execute code after the delay:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
sleep(10000).then(() => {
console.log('Blah blah blah blah extra-blah');
});