簡體   English   中英

如何在 Node.js/Javascript 中停止無限循環

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

如果我們使用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 沒有這種能力。

您需要這些循環來檢查循環外的內容(變量或調用函數或類似的東西),以便您能夠影響它們。

還有許多其他方法可以編寫可以受外部世界影響的循環。

一些例子:

  1. 使用setInterval()並從函數返回間隔 timerID。 然后,您可以調用clearInterval()來停止循環。

  2. 創建一個小對象,其中您的循環是一種方法,並讓該循環測試您可以從外部更改的實例變量。


PS 可能有一些技巧,你用構造函數替換Promise會強制拒絕,這會導致await拋出,然后包含async函數在下一個周期拒絕,但我假設你不是在尋找那種級別的 hack和環境的入侵。

由於sleep()被聲明為const您無法替換它會拒絕的替代品。

如果您想要對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