How can I wait In Node.js (JavaScript)? l need to pause for a period of time
Posted By: Anonymous
I’m developing a console script for personal needs. I need to be able to pause for an extended amount of time, but, from my research, Node.js has no way to stop as required. It’s getting hard to read users’ information after a period of time… I’ve seen some code out there, but I believe they have to have other code inside of them for them to work such as:
setTimeout(function() {
}, 3000);
However, I need everything after this line of code to execute after the period of time.
For example,
// start of code
console.log('Welcome to my console,');
some-wait-code-here-for-ten-seconds...
console.log('Blah blah blah blah extra-blah');
// end of code
I’ve also seen things like
yield sleep(2000);
But Node.js doesn’t recognize this.
How can I achieve this extended pause?
Solution
Best way to do this is to break your code into multiple functions, like this:
function function1() {
// stuff you want to happen right away
console.log('Welcome to My Console,');
}
function function2() {
// all the stuff you want to happen after that pause
console.log('Blah blah blah blah extra-blah');
}
// call the first chunk of code right away
function1();
// call the rest of the code and have it execute after 3 seconds
setTimeout(function2, 3000);
It’s similar to JohnnyHK‘s solution, but much neater and easier to extend.
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.