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

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


当前回答

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

node。js遵循,

process.nextTick()

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

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

其他回答

将你想要在延迟后执行的代码放在setTimeout回调函数中:

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

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

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

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

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

import { setTimeout } from 'timers/promises'

console.log('before')
await setTimeout(3000)
console.log('after')
function doThen(conditional,then,timer) {
    var timer = timer || 1;
    var interval = setInterval(function(){
        if(conditional()) {
            clearInterval(interval);
            then();
        }
    }, timer);
}

使用示例:

var counter = 1;
doThen(
    function() {
        counter++;
        return counter == 1000;
    },
    function() {
        console.log("Counter hit 1000"); // 1000 repeats later
    }
)

为了在javascript中“等待”,使用承诺是一种方法,正如上面的答案所示。

那么如何使用它呢?

下面是一个简单的例子,一个5秒的子进程以非阻塞的方式为一个4秒的主进程排队参数。

const wait = (seconds) => 
    new Promise(resolve => 
        setTimeout(() => 
            resolve(true), seconds * 1000))

const process = async (items, prepTask, mainTask) => {
    const queue = [];
    let done = false;

    items.forEach((item, i) => {
        prepTask(item).then(() => {
            queue.push(item);
            if (i == items.length -1) {
                done = true;
            }
        })
    })

    while (!done || queue.length) {
        if (queue.length) {
            const workload = queue.shift();
            await mainTask(workload)
        } else {
            console.log('waiting for subtask to queue')
            await wait(1);
        }
    }
}

// Usage Example

const ids = [1,2,3,4,5,6,7,8,9,10];

const prepTask = async (id) => {
    await wait(id * 5)
    return id * 5;
}

const mainTask = async (workload) => {
    console.log('excuting workload: ', workload);
    const result = await wait(4);
    return { workload, result }
}

process(ids, prepTask, mainTask)
    .then(() => console.log('done'))