我怎么能在Node.js(Javascript)中等待,我需要暂停一段时间 [英] How Can I Wait In Node.js (Javascript), l need to pause for a period of time
问题描述
我正在为个人需求开发类似脚本的控制台。我需要能够暂停一段时间,但是,根据我的研究,node.js无法按要求停止。在一段时间后很难读取用户的信息......我已经看到了一些代码,但我相信他们必须在其中包含其他代码才能使用它们:
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:
setTimeout(function() {
}, 3000);
但是,我需要在这段代码之后执行一段时间之后的所有内容。
However, I need everything after this line of code to execute after the period of time.
例如,
//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.
我也见过像
yield sleep(2000);
但是node.js无法识别这一点。
But node.js doesnt recognize this.
如何实现这种延长的暂停?
How can I achieve this extended pause?
推荐答案
最好的方法是将代码分解为多个函数,如这个:
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);
它类似于 JohnnyHK 的解决方案,但更简洁,更容易延伸。
It's similar to JohnnyHK's solution, but much neater and easier to extend.
这篇关于我怎么能在Node.js(Javascript)中等待,我需要暂停一段时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!