我正在为个人需求开发一个控制台脚本。我需要能够暂停更长的时间,但是,根据我的研究,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不能识别这个。

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


当前回答

从Node.js 15及以上版本开始,你可以使用Timers Promises API。您不再需要承诺setTimeout或依赖第三方库。

import { setTimeout } from 'timers/promises';

await setTimeout(1000);

其他回答

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

import { setTimeout } from 'timers/promises'

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

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

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

有关更多信息

yield sleep(2000); 

你应该检查Redux-Saga。但是它是特定于您选择Redux作为模型框架的(尽管严格来说不是必需的)。

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

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的解决方案,但更整洁,更容易扩展。

Node 7.6.0或更高版本

节点支持本地等待:

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

然后如果你可以使用异步函数:

await sleep(10000); // sleep for 10 seconds

or:

sleep(10000).then(() => {
  // This will execute 10 seconds from now
});

在较旧的Node版本上(原始答案)

我想要一个在Windows和Linux中工作的异步睡眠,而不会占用CPU很长的while循环。我尝试了睡眠包,但它无法安装在我的Windows盒子上。我最终使用:

https://www.npmjs.com/package/system-sleep

要安装它,输入:

npm install system-sleep

在你的代码中,

var sleep = require('system-sleep');
sleep(10*1000); // sleep for 10 seconds

效果非常好。