如何在Node.js(JavaScript)中等待?我需要暂停一段时间 [英] How can I wait In Node.js (JavaScript)? l need to pause for a period of time

查看:432
本文介绍了如何在Node.js(JavaScript)中等待?我需要暂停一段时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发满足个人需求的控制台脚本.我需要能够暂停很长一段时间,但是,根据我的研究,Node.js无法按需停止.一段时间后,读取用户的信息变得越来越困难……我已经看到了一些代码,但是我相信他们必须在其中包含其他代码才能使他们工作,例如:

I'm developing a console script for personal needs. I need to be able to pause for an 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');
    // end of code

我也看过类似的东西

    yield sleep(2000);

但是Node.js无法识别这一点.

But Node.js doesn't 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆