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

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


当前回答

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

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

其他回答

这是一个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;

有关更多信息

yield sleep(2000); 

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

由于javascript引擎(v8)是基于事件队列中的事件顺序运行代码的,因此没有严格的规定javascript在指定的时间后准确地触发执行。也就是说,当您设置几秒后执行代码时,触发代码完全基于事件队列中的顺序。因此,触发代码执行的时间可能会超过指定的时间。

node。js遵循,

process.nextTick()

来代替setTimeout()运行代码。例如,

process.nextTick(function(){
    console.log("This will be printed later");
});

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

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

import { setTimeout } from 'timers/promises'

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