如何在 Node.js (Javascript) 中等待,我需要暂停一段时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14249506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Can I Wait In Node.js (Javascript), l need to pause for a period of time
提问by Christopher Allen
I'm developing a console like script for personal needs. I need to be able to pause for a extended amount of time, but, from my research, node.js has no way to stop as required. It's getting hard to read users' information after a period of time... I've seen some code out there, but I believe they have to have other code inside of them for them to work such as:
我正在为个人需求开发一个类似脚本的控制台。我需要能够暂停很长时间,但是,根据我的研究,node.js 无法按要求停止。一段时间后,阅读用户信息变得越来越困难......我已经看到了一些代码,但我相信他们必须在其中包含其他代码才能工作,例如:
setTimeout(function() {
}, 3000);
However, I need everything after this line of code to execute after the period of time.
但是,我需要在这行代码之后的所有内容在一段时间后执行。
For example,
例如,
//start-of-code
console.log('Welcome to My Console,');
some-wait-code-here-for-ten-seconds..........
console.log('Blah blah blah blah extra-blah');
//endcode.
I've also seen things like
我也看过类似的东西
yield sleep(2000);
But node.js doesnt recognize this.
但是 node.js 不承认这一点。
How can I achieve this extended pause?
我怎样才能实现这种延长的暂停?
采纳答案by Elliot Bonneville
Best way to do this is to break your code into multiple functions, like this:
最好的方法是将您的代码分解为多个函数,如下所示:
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);
It's similar to JohnnyHK's solution, but much neater and easier to extend.
它类似于JohnnyHK的解决方案,但更简洁,更易于扩展。
回答by Aminadav Glickshtein
A new answer to an old question. Today ( Jan 2017June 2019) it is much easier. You can use the new async/awaitsyntax.
For example:
一个老问题的新答案。今天(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);
});
}
For using async/awaitout of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmonyflag.
要async/await在不安装和插件的情况下开箱即用,您必须使用 node-v7 或 node-v8,并使用该--harmony标志。
Update June 2019:By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.
2019 年 6 月更新:通过使用最新版本的 NodeJS,您可以开箱即用。无需提供命令行参数。今天甚至谷歌浏览器都支持它。
Update May 2020:Soon you will be able to use the awaitsyntax outside of an async function. In the top level like in this example
2020 年 5 月更新:很快您将能够在await异步函数之外使用语法。在这个例子中的顶层
await sleep(1000)
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
The proposal is in stage 3. You can use it today by using webpack 5 (alpha),
该提案处于第 3 阶段。你今天可以通过使用 webpack 5 (alpha) 来使用它,
More info:
更多信息:
- Harmony Flag in Nodejs: https://nodejs.org/en/docs/es6/
- All NodeJS Version for download: https://nodejs.org/en/download/releases/
- Nodejs 中的和谐标志:https://nodejs.org/en/docs/es6/
- 所有 NodeJS 版本下载:https: //nodejs.org/en/download/releases/
回答by k06a
The shortest solution without any dependencies:
没有任何依赖的最短解决方案:
await new Promise(resolve => setTimeout(resolve, 5000));
回答by JohnnyHK
Put the code that you want executed after the delay within the setTimeoutcallback:
将您要在延迟后执行的代码放入setTimeout回调中:
console.log('Welcome to My Console,');
setTimeout(function() {
console.log('Blah blah blah blah extra-blah');
}, 3000);
回答by atlex2
This is a simple blocking technique:
这是一个简单的阻塞技术:
var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}
It's blockinginsofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!
它是阻塞的,因为您的脚本中不会发生任何其他事情(如回调)。但由于这是一个控制台脚本,也许它正是您所需要的!
回答by Ryan Shillington
On Node 7.6.0 or higher
在 Node 7.6.0 或更高版本上
Node supports waiting natively:
Node 支持原生等待:
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
then if you can use async functions:
那么如果你可以使用异步函数:
await sleep(10000); // sleep for 10 seconds
or:
或者:
sleep(10000).then(() => {
// This will execute 10 seconds from now
});
On older Node versions (original answer)
在较旧的 Node 版本上(原始答案)
I wanted an asynchronous sleep that worked in Windows & Linux, without hogging my CPU with a long while loop. I tried the sleep package but it wouldn't install on my Windows box. I ended up using:
我想要一个在 Windows 和 Linux 中工作的异步睡眠,而不会因长时间循环而占用我的 CPU。我尝试了 sleep 包,但它不会安装在我的 Windows 机器上。我最终使用了:
https://www.npmjs.com/package/system-sleep
https://www.npmjs.com/package/system-sleep
To install it, type:
要安装它,请键入:
npm install system-sleep
In your code,
在您的代码中,
var sleep = require('system-sleep');
sleep(10*1000); // sleep for 10 seconds
Works like a charm.
奇迹般有效。
回答by Lucio Paiva
Simple and elegant sleep function using modern Javascript
使用现代Javascript的简单优雅的睡眠功能
function sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}
No dependencies, no callback hell; that's it :-)
没有依赖,没有回调地狱;就是这样 :-)
Considering the example given in the question, this is how we would sleep between two console logs:
考虑到问题中给出的示例,这就是我们在两个控制台日志之间睡眠的方式:
async function main() {
console.log("Foo");
await sleep(2000);
console.log("Bar");
}
main();
The "drawback" is that your main function now has to be asyncas well. But, considering you are already writing modern Javascript code, you are probably (or at least should be!) using async/awaitall over your code, so this is really not an issue. All modern browsers today supportit.
“缺点”是您的主要功能现在也必须async如此。但是,考虑到您已经在编写现代 Javascript 代码,您可能(或至少应该!)在您的代码中使用async/ await,所以这真的不是问题。今天所有的现代浏览器都支持它。
Giving a little insight into the sleepfunction for those that are not used to async/awaitand fat arrow operators, this is the verbose way of writing it:
sleep为那些不习惯async/await和粗箭头运算符的人提供一些有关该函数的见解,这是编写它的冗长方式:
function sleep(millis) {
return new Promise(function (resolve, reject) {
setTimeout(function () { resolve(); }, millis);
});
}
Using the fat arrow operator, though, makes it even smaller (and more elegant).
但是,使用粗箭头运算符可以使它更小(更优雅)。
回答by Aleksej
You can use this www.npmjs.com/package/sleep
你可以使用这个www.npmjs.com/package/sleep
var sleep = require('sleep');
sleep.sleep(10); // sleep for ten seconds
回答by jmar777
This question is quite old, but recently V8 has added Generators which can accomplish what the OP requested. Generators are generally easiest to use for async interactions with the assistance of a library such as suspendor gen-run.
这个问题已经很老了,但最近 V8 添加了可以完成 OP 要求的生成器。在诸如suspend或gen-run之类的库的帮助下,生成器通常最容易用于异步交互。
Here's an example using 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');
})();
Related reading (by way of shameless self promotion): What's the Big Deal with Generators?.
相关阅读(通过无耻的自我宣传):发电机有什么大不了的?.
回答by Bart Verheijen
On Linux/nodejs this works for me:
在 Linux/nodejs 上,这对我有用:
const spawnSync = require('child_process').spawnSync;
var sleep = spawnSync('sleep', [1.5]);
const spawnSync = require('child_process').spawnSync;
var sleep = spawnSync('sleep', [1.5]);
It is blocking, but it is not a busy wait loop.
它是阻塞的,但它不是一个繁忙的等待循环。
The time you specify is in seconds but can be a fraction. I don't know if other OS's have a similar command.
您指定的时间以秒为单位,但可以是一小部分。我不知道其他操作系统是否有类似的命令。

