如果我们使用 worker('hello')
和 worker('world')
启动 2 个并发无限循环,我们稍后如何停止其中一个循环?
例如:
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)
})();
最佳答案
您无法从函数外部停止这些 worker()
循环。 JavaScript 不具备这种能力。
您需要这些循环检查循环之外的内容(变量或调用函数或类似的内容),以便您能够影响它们。
还有许多其他方式来编写可以受到外界影响的循环。
一些例子:
使用
setInterval()
并从函数返回间隔计时器ID。然后,您可以调用clearInterval()
来停止循环。创建一个小对象,其中循环是一种方法,并让该循环测试可以从外部更改的实例变量。
附注可能存在一些黑客行为,您将 Promise
替换为构造函数,该构造函数会强制拒绝,从而导致 await
抛出,然后包含 async
函数在下一个周期拒绝,但我认为您并不是在寻找那种程度的黑客攻击和对环境的入侵。
由于 sleep()
被声明为 const
,因此您无法破解会拒绝的替代品。
关于javascript - 如何停止 Node.js/Javascript 中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60944570/