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

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


当前回答

简单,我们将等待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;
        }
    })();

其他回答

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

import { setTimeout } from 'timers/promises';

await setTimeout(1000);

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

如果你真正想要的只是在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表示不缓冲输出。

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

import { setTimeout } from 'timers/promises'

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

在Linux/nodejs上,这对我来说是有效的:

const spawnSync = require('child_process').spawnSync; var sleep = spawnSync('sleep', [1.5]);

它正在阻塞,但它不是一个繁忙等待循环。

您指定的时间以秒为单位,但可以是分数。我不知道其他操作系统是否有类似的命令。

我最近创建了一个更简单的抽象概念,叫做等待。用于在同步模式下调用异步函数(基于节点光纤)。还有一个基于即将到来的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模式下调用。 检查例子。