How Can I Wait In Node.js (Javascript), l need to pause for a period of time

How Can I Wait In Node.js (Javascript), l need to pause for a period of time

I’m developing a console like script for personal needs. I need to be able to pause for a 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’);
//endcode.

I’ve also seen things like
yield sleep(2000);

But node.js doesnt recognize this.
How can I achieve this extended pause?

Solutions/Answers:

Solution 1:

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.

Related:  Javascript if in x [duplicate]

Solution 2:

A new answer to an old question. Today ( Jan 2017 June 2019) it is much easier. You can use the new async/await syntax.
For example:

async function init(){
   console.log(1)
   await sleep(1000)
   console.log(2)
}
function sleep(ms){
    return new Promise(resolve=>{
        setTimeout(resolve,ms)
    })
}

For using async/await out of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmony flag.

Update June 2019: By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.

More info:

Solution 3:

Put the code that you want executed after the delay within the setTimeout callback:

console.log('Welcome to My Console,');
setTimeout(function() {
    console.log('Blah blah blah blah extra-blah');
}, 3000);

Solution 4:

This is a simple blocking technique:

var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}

It’s blocking insofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!

Related:  How to easily create Github friendly markdown for documented JavaScript functions?

Solution 5:

The shortest solution without any dependencies:

await new Promise(done => setTimeout(done, 5000));

Solution 6:

Simple and elegant sleep function using modern Javascript

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

No dependencies, no callback hell; that’s it 🙂


Considering the example given in the question, this is how we would sleep between two console logs:

async function main() {
    console.log("Foo");
    await sleep(2000);
    console.log("Bar");
}

main();

The “drawback” is that your main function now has to be async as well. But, considering you are already writing modern Javascript code, you are probably (or at least should be!) using async/await all over your code, so this is really not an issue. All modern browsers today support it.

Giving a little insight into the sleep function for those that are not used to async/await and fat arrow operators, this is the verbose way of writing it:

function sleep(millis) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () { resolve(); }, millis);
    });
}

Using the fat arrow operator, though, makes it even smaller (and more elegant).

Related:  D3 - how to deal with JSON data structures?