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

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


当前回答

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

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

其他回答

你可以使用这个www.npmjs.com/package/sleep

var sleep = require('sleep');
sleep.sleep(10); // sleep for ten seconds

这是一个简单的阻塞技巧:

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

如果脚本中没有其他事情发生(比如回调),那么它就是阻塞的。但由于这是一个控制台脚本,也许它就是您所需要的!

对于一些人来说,接受的答案是不工作的,我发现了这个其他的答案,它是为我工作:我如何传递一个参数setTimeout()回调?

var hello = "Hello World";
setTimeout(alert, 1000, hello); 

'hello'是正在传递的参数,您可以在超时时间后传递所有参数。感谢@Fabio Phms的回答。

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

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

我最近创建了一个更简单的抽象概念,叫做等待。用于在同步模式下调用异步函数(基于节点光纤)。还有一个基于即将到来的ES6生成器的版本。

https://github.com/luciotato/waitfor

使用等。对于,你可以调用任何标准的nodejs async函数,就像它是一个同步函数一样,而不会阻塞node的事件循环。

您可以在需要时按顺序编码,这(我猜)完美地简化了您的脚本供个人使用。

使用等。你的代码将是:

require('waitfor')

..in a fiber..
//start-of-code
console.log('Welcome to My Console,');
wait.miliseconds(10*1000); //defined in waitfor/paralell-tests.js - DOES NOT BLOCK
console.log('Blah blah blah blah extra-blah');
//endcode. 

同样,任何async函数都可以在Sync模式下调用。 检查例子。