我正在为个人需求开发一个控制台脚本。我需要能够暂停更长的时间,但是,根据我的研究,Node.js没有办法根据需要停止。一段时间后,读取用户信息变得越来越困难了……我已经看到了一些代码,但我相信他们必须有其他的代码在他们的工作,如:

    setTimeout(function() {
    }, 3000);

但是,我需要这行代码之后的所有内容在一段时间之后执行。

例如,

    // 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

我还见过

    yield sleep(2000);

但是Node.js不能识别这个。

我怎样才能实现这种延长的暂停?


当前回答

如果你想“编码高尔夫”,你可以在这里制作一些其他答案的简短版本:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

但在我看来,真正理想的答案是使用Node的util库和它的promisify函数,它正是为这类事情而设计的(为先前存在的基于承诺的东西制作基于承诺的版本):

const util = require('util');
const sleep = util.promisify(setTimeout);

在任何一种情况下,你都可以使用await调用你的睡眠函数来暂停:

await sleep(1000); // sleep for 1s/1000ms

编辑:正如评论中所指出的,你甚至可以把它减少到一行:

const sleep = require('util').promisify(setTimeout);

或者,如果你甚至不想费心创建一个睡眠函数:

await require('util').promisify(setTimeout)(1000);

其他回答

简单,我们将等待5秒钟来等待一些事件发生(这将由done变量在代码中的其他地方设置为true表示),或者当超时到期时,我们将每100ms检查一次

    var timeout=5000; //will wait for 5 seconds or untildone
    var scope = this; //bind this to scope variable
    (function() {
        if (timeout<=0 || scope.done) //timeout expired or done
        {
            scope.callback();//some function to call after we are done
        }
        else
        {
            setTimeout(arguments.callee,100) //call itself again until done
            timeout -= 100;
        }
    })();

将你想要在延迟后执行的代码放在setTimeout回调函数中:

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

尝试使用promise,它在NodeJS中很管用

一个衬套

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

或者把它作为NodeJS中的一个函数来重用

const sleep = async (milliseconds) => {
    await new Promise(resolve => setTimeout(resolve, milliseconds));
}

像这样使用函数

await sleep(5000)

节点16有一种新的方法可以轻松地完成它

import { setTimeout } from 'timers/promises'

console.log('before')
await setTimeout(3000)
console.log('after')

最好的方法是把你的代码分解成多个函数,像这样:

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);

它类似于JohnnyHK的解决方案,但更整洁,更容易扩展。