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

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


当前回答

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

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

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

其他回答

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

如果你真正想要的只是在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')

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

2021年1月更新:你甚至可以在Node REPL交互中使用——experimental-repl-await标志来实现

$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.

老问题的新答案。今天(2017年1月至2019年6月)要容易得多。您可以使用新的async/await语法。 例如:

async function init() {
  console.log(1);
  await sleep(1000);
  console.log(2);
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

为了在不安装插件的情况下使用async/await,你必须使用node-v7或node-v8,并使用——harmony标志。

2019年6月更新:通过使用最新版本的NodeJS,您可以开箱即用。不需要提供命令行参数。即使谷歌Chrome今天也支持它。

2020年5月更新: 很快你就可以在async函数之外使用await语法了。在顶层,比如这个例子

await sleep(1000)
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

提案已进入第三阶段。 今天你可以通过webpack 5 (alpha)使用它,

更多信息:

Nodejs中的和谐标志:https://nodejs.org/en/docs/es6/ 所有NodeJS版本下载:https://nodejs.org/en/download/releases/

let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));

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

This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function keyword followed by a * is called a generator function in modern Javascript. The npm package co provided a runner function to run a generator.

本质上,生成器函数提供了一种使用yield关键字暂停函数执行的方法,同时,生成器函数中的yield使生成器内部和调用者之间交换信息成为可能。这为调用方提供了一种机制,可以从异步调用的promise中提取数据,并将已解析的数据传递回生成器。实际上,它使异步调用同步化。