简体   繁体   中英

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?

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. Javascript does not have that capability.

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. Then, you can call clearInterval() to stop the loop.

  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.

Since sleep() is declared as const you can't hack in a replacement for it that would reject.

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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