简体   繁体   English

如何在 Node.js/Javascript 中停止无限循环

[英]How To Stop An Infinite Loop in Node.js/Javascript

If we started 2 concurrent infinite loops using worker('hello') and worker('world') , how can we later stop one of the loops?如果我们使用worker('hello')worker('world')启动了 2 个并发的无限循环,我们以后如何停止其中一个循环?

For example:例如:

const sleep = async function (duration) {
    await new Promise(r => setTimeout(r, duration));
}

const worker = async (id) => {
    while (true) {
        console.log(id);
        await sleep(2000);  // simulates a blocking call
    }
}

(async () => {
    const hello = worker('hello')
    const world = worker('world')

    // Let's assume that now a user-input requires us to stop the `worker('hello')`
    setTimeout(() => {
        console.log('stopping hello...')\
        // how to stop 'hello'?
    }, 5000)
})();

You cannot stop those worker() loops from outside of the function.您无法从函数外部停止那些worker()循环。 Javascript does not have that capability. Javascript 没有这种能力。

You would need those loops to be checking something that is outside the loop (a variable or calling a function or something like that) for you to be able to influence them.您需要这些循环来检查循环外的内容(变量或调用函数或类似的东西),以便您能够影响它们。

There are many other ways to write the loop that can be influenced from the outside world.还有许多其他方法可以编写可以受外部世界影响的循环。

Some examples:一些例子:

  1. Use setInterval() and return the interval timerID from the function.使用setInterval()并从函数返回间隔 timerID。 Then, you can call clearInterval() to stop the loop.然后,您可以调用clearInterval()来停止循环。

  2. Create a small object where your loop is one method and have that loop test an instance variable that you can change from the outside.创建一个小对象,其中您的循环是一种方法,并让该循环测试您可以从外部更改的实例变量。


PS There might be some hacks where you replace Promise with a constructor that would force a reject which would cause the await to throw and then containing async function to reject on the next cycle, but I assume you're not looking for that level of hack and invasion of the environment. PS 可能有一些技巧,你用构造函数替换Promise会强制拒绝,这会导致await抛出,然后包含async函数在下一个周期拒绝,但我假设你不是在寻找那种级别的 hack和环境的入侵。

Since sleep() is declared as const you can't hack in a replacement for it that would reject.由于sleep()被声明为const您无法替换它会拒绝的替代品。

If the only thing you want to do with the worker function is to repeat some action every N milliseconds, I suggest using setInterval explained here如果您想要对worker函数做的唯一一件事是每 N 毫秒重复一些操作,我建议使用setInterval解释here

function worker(id) {
    return setInterval(() => {//loop actions inside this annonymous function
        console.log(id);
        //Anything else

    }, 2000);//Every 2000 milliseconds
}

//make a loop active
const intervalHello = worker(`Hello`);
//stop the interval
clearInterval(intervalHello);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM