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

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


当前回答

其他的答案都很好,但我想我要采取不同的策略。

如果你真正想要的只是在linux中减慢一个特定的文件:

 rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile  &

节点myprog slowfile

这将每5行休眠1秒。节点程序将和写入程序一样慢。如果它在做其他事情,它们将继续以正常速度运行。

mkfifo创建了一个先进先出管道。这就是它的作用。 perl行可以像你想要的那样快。$|=1表示不缓冲输出。

其他回答

function doThen(conditional,then,timer) {
    var timer = timer || 1;
    var interval = setInterval(function(){
        if(conditional()) {
            clearInterval(interval);
            then();
        }
    }, timer);
}

使用示例:

var counter = 1;
doThen(
    function() {
        counter++;
        return counter == 1000;
    },
    function() {
        console.log("Counter hit 1000"); // 1000 repeats later
    }
)

这个问题很老了,但是最近V8增加了生成器,可以完成OP的请求。在挂起或gen-run等库的帮助下,生成器通常最容易用于异步交互。

下面是一个使用suspend的例子:

suspend(function* () {
    console.log('Welcome to My Console,');
    yield setTimeout(suspend.resume(), 10000); // 10 seconds pass..
    console.log('Blah blah blah blah extra-blah');
})();

相关阅读(通过无耻的自我宣传):发电机有什么大不了的?

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

import { setTimeout } from 'timers/promises';

await setTimeout(1000);

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

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

这是一个moment.js风格的模块,基于@atlex2建议的脏块方法。仅用于测试。

const moment = require('moment');

let sleep = (secondsToSleep = 1) => {
    let sleepUntill = moment().add(secondsToSleep, 'seconds');
    while(moment().isBefore(sleepUntill)) { /* block the process */ }
}

module.exports = sleep;